1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545
|
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import static com.android.internal.util.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SuppressLint;
import android.annotation.TestApi;
import android.app.AppOpsManager;
import android.compat.annotation.UnsupportedAppUsage;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.ExceptionUtils;
import android.util.Log;
import android.util.MathUtils;
import android.util.Pair;
import android.util.Size;
import android.util.SizeF;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.ArrayUtils;
import dalvik.annotation.optimization.CriticalNative;
import dalvik.annotation.optimization.FastNative;
import libcore.util.SneakyThrow;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Supplier;
/**
* Container for a message (data and object references) that can
* be sent through an IBinder. A Parcel can contain both flattened data
* that will be unflattened on the other side of the IPC (using the various
* methods here for writing specific types, or the general
* {@link Parcelable} interface), and references to live {@link IBinder}
* objects that will result in the other side receiving a proxy IBinder
* connected with the original IBinder in the Parcel.
*
* <p class="note">Parcel is <strong>not</strong> a general-purpose
* serialization mechanism. This class (and the corresponding
* {@link Parcelable} API for placing arbitrary objects into a Parcel) is
* designed as a high-performance IPC transport. As such, it is not
* appropriate to place any Parcel data in to persistent storage: changes
* in the underlying implementation of any of the data in the Parcel can
* render older data unreadable.</p>
*
* <p>The bulk of the Parcel API revolves around reading and writing data
* of various types. There are six major classes of such functions available.</p>
*
* <h3>Primitives</h3>
*
* <p>The most basic data functions are for writing and reading primitive
* data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
* {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
* {@link #readInt}, {@link #writeLong}, {@link #readLong},
* {@link #writeString}, {@link #readString}. Most other
* data operations are built on top of these. The given data is written and
* read using the endianess of the host CPU.</p>
*
* <h3>Primitive Arrays</h3>
*
* <p>There are a variety of methods for reading and writing raw arrays
* of primitive objects, which generally result in writing a 4-byte length
* followed by the primitive data items. The methods for reading can either
* read the data into an existing array, or create and return a new array.
* These available types are:</p>
*
* <ul>
* <li> {@link #writeBooleanArray(boolean[])},
* {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
* <li> {@link #writeByteArray(byte[])},
* {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
* {@link #createByteArray()}
* <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
* {@link #createCharArray()}
* <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
* {@link #createDoubleArray()}
* <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
* {@link #createFloatArray()}
* <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
* {@link #createIntArray()}
* <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
* {@link #createLongArray()}
* <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
* {@link #createStringArray()}.
* <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
* {@link #readSparseBooleanArray()}.
* </ul>
*
* <h3>Parcelables</h3>
*
* <p>The {@link Parcelable} protocol provides an extremely efficient (but
* low-level) protocol for objects to write and read themselves from Parcels.
* You can use the direct methods {@link #writeParcelable(Parcelable, int)}
* and {@link #readParcelable(ClassLoader)} or
* {@link #writeParcelableArray} and
* {@link #readParcelableArray(ClassLoader)} to write or read. These
* methods write both the class type and its data to the Parcel, allowing
* that class to be reconstructed from the appropriate class loader when
* later reading.</p>
*
* <p>There are also some methods that provide a more efficient way to work
* with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
* {@link #writeTypedList}, {@link #readTypedObject},
* {@link #createTypedArray} and {@link #createTypedArrayList}. These methods
* do not write the class information of the original object: instead, the
* caller of the read function must know what type to expect and pass in the
* appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
* properly construct the new object and read its data. (To more efficient
* write and read a single Parcelable object that is not null, you can directly
* call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
* {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
* yourself.)</p>
*
* <h3>Bundles</h3>
*
* <p>A special type-safe container, called {@link Bundle}, is available
* for key/value maps of heterogeneous values. This has many optimizations
* for improved performance when reading and writing data, and its type-safe
* API avoids difficult to debug type errors when finally marshalling the
* data contents into a Parcel. The methods to use are
* {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
* {@link #readBundle(ClassLoader)}.
*
* <h3>Active Objects</h3>
*
* <p>An unusual feature of Parcel is the ability to read and write active
* objects. For these objects the actual contents of the object is not
* written, rather a special token referencing the object is written. When
* reading the object back from the Parcel, you do not get a new instance of
* the object, but rather a handle that operates on the exact same object that
* was originally written. There are two forms of active objects available.</p>
*
* <p>{@link Binder} objects are a core facility of Android's general cross-process
* communication system. The {@link IBinder} interface describes an abstract
* protocol with a Binder object. Any such interface can be written in to
* a Parcel, and upon reading you will receive either the original object
* implementing that interface or a special proxy implementation
* that communicates calls back to the original object. The methods to use are
* {@link #writeStrongBinder(IBinder)},
* {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
* {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
* {@link #createBinderArray()},
* {@link #writeInterfaceArray(T[])}, {@link #readInterfaceArray(T[], Function)},
* {@link #createInterfaceArray(IntFunction, Function)},
* {@link #writeBinderList(List)}, {@link #readBinderList(List)},
* {@link #createBinderArrayList()},
* {@link #writeInterfaceList(List)}, {@link #readInterfaceList(List, Function)},
* {@link #createInterfaceArrayList(Function)}.</p>
*
* <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
* can be written and {@link ParcelFileDescriptor} objects returned to operate
* on the original file descriptor. The returned file descriptor is a dup
* of the original file descriptor: the object and fd is different, but
* operating on the same underlying file stream, with the same position, etc.
* The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
* {@link #readFileDescriptor()}.
*
* <h3>Parcelable Containers</h3>
*
* <p>A final class of methods are for writing and reading standard Java
* containers of arbitrary types. These all revolve around the
* {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
* which define the types of objects allowed. The container methods are
* {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
* {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
* {@link #readArrayList(ClassLoader)},
* {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
* {@link #writeSparseArray(SparseArray)},
* {@link #readSparseArray(ClassLoader)}.
*
* <h3>Restricted Parcelable Containers</h3>
*
* <p>A final class of methods are for reading standard Java containers of restricted types.
* These methods replace methods for reading containers of arbitrary types from previous section
* starting from Android {@link Build.VERSION_CODES#TIRAMISU}. The pairing writing methods are
* still the same from previous section.
* These methods accepts additional {@code clazz} parameters as the required types.
* The Restricted Parcelable container methods are {@link #readArray(ClassLoader, Class)},
* {@link #readList(List, ClassLoader, Class)},
* {@link #readArrayList(ClassLoader, Class)},
* {@link #readMap(Map, ClassLoader, Class, Class)},
* {@link #readSparseArray(ClassLoader, Class)}.
*/
public final class Parcel {
private static final boolean DEBUG_RECYCLE = false;
private static final boolean DEBUG_ARRAY_MAP = false;
private static final String TAG = "Parcel";
@UnsupportedAppUsage
@SuppressWarnings({"UnusedDeclaration"})
private long mNativePtr; // used by native code
/**
* Flag indicating if {@link #mNativePtr} was allocated by this object,
* indicating that we're responsible for its lifecycle.
*/
private boolean mOwnsNativeParcelObject;
private long mNativeSize;
private ArrayMap<Class, Object> mClassCookies;
private RuntimeException mStack;
private boolean mRecycled = false;
/** @hide */
@TestApi
public static final int FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT = 1 << 0;
/** @hide */
@TestApi
public static final int FLAG_PROPAGATE_ALLOW_BLOCKING = 1 << 1;
/** @hide */
@IntDef(flag = true, prefix = { "FLAG_" }, value = {
FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT,
FLAG_PROPAGATE_ALLOW_BLOCKING,
})
@Retention(RetentionPolicy.SOURCE)
public @interface ParcelFlags {}
@ParcelFlags
private int mFlags;
/**
* Whether or not to parcel the stack trace of an exception. This has a performance
* impact, so should only be included in specific processes and only on debug builds.
*/
private static boolean sParcelExceptionStackTrace;
private static final Object sPoolSync = new Object();
/** Next item in the linked list pool, if any */
@GuardedBy("sPoolSync")
private Parcel mPoolNext;
/** Head of a linked list pool of {@link Parcel} objects */
@GuardedBy("sPoolSync")
private static Parcel sOwnedPool;
/** Head of a linked list pool of {@link Parcel} objects */
@GuardedBy("sPoolSync")
private static Parcel sHolderPool;
/** Total size of pool with head at {@link #sOwnedPool} */
@GuardedBy("sPoolSync")
private static int sOwnedPoolSize = 0;
/** Total size of pool with head at {@link #sHolderPool} */
@GuardedBy("sPoolSync")
private static int sHolderPoolSize = 0;
/**
* We're willing to pool up to 32 objects, which is sized to accommodate
* both a data and reply Parcel for the maximum of 16 Binder threads.
*/
private static final int POOL_SIZE = 32;
// Keep in sync with frameworks/native/include/private/binder/ParcelValTypes.h.
private static final int VAL_NULL = -1;
private static final int VAL_STRING = 0;
private static final int VAL_INTEGER = 1;
private static final int VAL_MAP = 2; // length-prefixed
private static final int VAL_BUNDLE = 3;
private static final int VAL_PARCELABLE = 4; // length-prefixed
private static final int VAL_SHORT = 5;
private static final int VAL_LONG = 6;
private static final int VAL_FLOAT = 7;
private static final int VAL_DOUBLE = 8;
private static final int VAL_BOOLEAN = 9;
private static final int VAL_CHARSEQUENCE = 10;
private static final int VAL_LIST = 11; // length-prefixed
private static final int VAL_SPARSEARRAY = 12; // length-prefixed
private static final int VAL_BYTEARRAY = 13;
private static final int VAL_STRINGARRAY = 14;
private static final int VAL_IBINDER = 15;
private static final int VAL_PARCELABLEARRAY = 16; // length-prefixed
private static final int VAL_OBJECTARRAY = 17; // length-prefixed
private static final int VAL_INTARRAY = 18;
private static final int VAL_LONGARRAY = 19;
private static final int VAL_BYTE = 20;
private static final int VAL_SERIALIZABLE = 21; // length-prefixed
private static final int VAL_SPARSEBOOLEANARRAY = 22;
private static final int VAL_BOOLEANARRAY = 23;
private static final int VAL_CHARSEQUENCEARRAY = 24;
private static final int VAL_PERSISTABLEBUNDLE = 25;
private static final int VAL_SIZE = 26;
private static final int VAL_SIZEF = 27;
private static final int VAL_DOUBLEARRAY = 28;
private static final int VAL_CHAR = 29;
private static final int VAL_SHORTARRAY = 30;
private static final int VAL_CHARARRAY = 31;
private static final int VAL_FLOATARRAY = 32;
// The initial int32 in a Binder call's reply Parcel header:
// Keep these in sync with libbinder's binder/Status.h.
private static final int EX_SECURITY = -1;
private static final int EX_BAD_PARCELABLE = -2;
private static final int EX_ILLEGAL_ARGUMENT = -3;
private static final int EX_NULL_POINTER = -4;
private static final int EX_ILLEGAL_STATE = -5;
private static final int EX_NETWORK_MAIN_THREAD = -6;
private static final int EX_UNSUPPORTED_OPERATION = -7;
private static final int EX_SERVICE_SPECIFIC = -8;
private static final int EX_PARCELABLE = -9;
/** @hide */
// WARNING: DO NOT add more 'reply' headers. These also need to add work to native
// code and this encodes extra information in object statuses. If we need to expand
// this design, we should add a generic way to attach parcelables/structured parcelables
// to transactions which can work across languages.
public static final int EX_HAS_NOTED_APPOPS_REPLY_HEADER = -127; // special; see below
// WARNING: DO NOT add more 'reply' headers. These also need to add work to native
// code and this encodes extra information in object statuses. If we need to expand
// this design, we should add a generic way to attach parcelables/structured parcelables
// to transactions which can work across languages.
private static final int EX_HAS_STRICTMODE_REPLY_HEADER = -128; // special; see below
// EX_TRANSACTION_FAILED is used exclusively in native code.
// see libbinder's binder/Status.h
private static final int EX_TRANSACTION_FAILED = -129;
@CriticalNative
private static native void nativeMarkSensitive(long nativePtr);
@FastNative
private static native void nativeMarkForBinder(long nativePtr, IBinder binder);
@CriticalNative
private static native boolean nativeIsForRpc(long nativePtr);
@CriticalNative
private static native int nativeDataSize(long nativePtr);
@CriticalNative
private static native int nativeDataAvail(long nativePtr);
@CriticalNative
private static native int nativeDataPosition(long nativePtr);
@CriticalNative
private static native int nativeDataCapacity(long nativePtr);
@FastNative
private static native void nativeSetDataSize(long nativePtr, int size);
@CriticalNative
private static native void nativeSetDataPosition(long nativePtr, int pos);
@FastNative
private static native void nativeSetDataCapacity(long nativePtr, int size);
@CriticalNative
private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
@CriticalNative
private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len);
private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len);
@CriticalNative
private static native int nativeWriteInt(long nativePtr, int val);
@CriticalNative
private static native int nativeWriteLong(long nativePtr, long val);
@CriticalNative
private static native int nativeWriteFloat(long nativePtr, float val);
@CriticalNative
private static native int nativeWriteDouble(long nativePtr, double val);
private static native void nativeSignalExceptionForError(int error);
@FastNative
private static native void nativeWriteString8(long nativePtr, String val);
@FastNative
private static native void nativeWriteString16(long nativePtr, String val);
@FastNative
private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
@FastNative
private static native void nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
private static native byte[] nativeCreateByteArray(long nativePtr);
private static native boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen);
private static native byte[] nativeReadBlob(long nativePtr);
@CriticalNative
private static native int nativeReadInt(long nativePtr);
@CriticalNative
private static native long nativeReadLong(long nativePtr);
@CriticalNative
private static native float nativeReadFloat(long nativePtr);
@CriticalNative
private static native double nativeReadDouble(long nativePtr);
@FastNative
private static native String nativeReadString8(long nativePtr);
@FastNative
private static native String nativeReadString16(long nativePtr);
@FastNative
private static native IBinder nativeReadStrongBinder(long nativePtr);
@FastNative
private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
private static native long nativeCreate();
private static native void nativeFreeBuffer(long nativePtr);
private static native void nativeDestroy(long nativePtr);
private static native byte[] nativeMarshall(long nativePtr);
private static native void nativeUnmarshall(
long nativePtr, byte[] data, int offset, int length);
private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
private static native boolean nativeCompareDataInRange(
long ptrA, int offsetA, long ptrB, int offsetB, int length);
private static native void nativeAppendFrom(
long thisNativePtr, long otherNativePtr, int offset, int length);
@CriticalNative
private static native boolean nativeHasFileDescriptors(long nativePtr);
private static native boolean nativeHasFileDescriptorsInRange(
long nativePtr, int offset, int length);
private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
@CriticalNative
private static native boolean nativeReplaceCallingWorkSourceUid(
long nativePtr, int workSourceUid);
@CriticalNative
private static native int nativeReadCallingWorkSourceUid(long nativePtr);
/** Last time exception with a stack trace was written */
private static volatile long sLastWriteExceptionStackTrace;
/** Used for throttling of writing stack trace, which is costly */
private static final int WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS = 1000;
@CriticalNative
private static native long nativeGetOpenAshmemSize(long nativePtr);
public final static Parcelable.Creator<String> STRING_CREATOR
= new Parcelable.Creator<String>() {
public String createFromParcel(Parcel source) {
return source.readString();
}
public String[] newArray(int size) {
return new String[size];
}
};
/**
* @hide
*/
public static class ReadWriteHelper {
@UnsupportedAppUsage
public ReadWriteHelper() {
}
public static final ReadWriteHelper DEFAULT = new ReadWriteHelper();
/**
* Called when writing a string to a parcel. Subclasses wanting to write a string
* must use {@link #writeStringNoHelper(String)} to avoid
* infinity recursive calls.
*/
public void writeString8(Parcel p, String s) {
p.writeString8NoHelper(s);
}
public void writeString16(Parcel p, String s) {
p.writeString16NoHelper(s);
}
/**
* Called when reading a string to a parcel. Subclasses wanting to read a string
* must use {@link #readStringNoHelper()} to avoid
* infinity recursive calls.
*/
public String readString8(Parcel p) {
return p.readString8NoHelper();
}
public String readString16(Parcel p) {
return p.readString16NoHelper();
}
}
private ReadWriteHelper mReadWriteHelper = ReadWriteHelper.DEFAULT;
/**
* Retrieve a new Parcel object from the pool.
*/
@NonNull
public static Parcel obtain() {
Parcel res = null;
synchronized (sPoolSync) {
if (sOwnedPool != null) {
res = sOwnedPool;
sOwnedPool = res.mPoolNext;
res.mPoolNext = null;
sOwnedPoolSize--;
}
}
// When no cache found above, create from scratch; otherwise prepare the
// cached object to be used
if (res == null) {
res = new Parcel(0);
} else {
res.mRecycled = false;
if (DEBUG_RECYCLE) {
res.mStack = new RuntimeException();
}
res.mReadWriteHelper = ReadWriteHelper.DEFAULT;
}
return res;
}
/**
* Retrieve a new Parcel object from the pool for use with a specific binder.
*
* Associate this parcel with a binder object. This marks the parcel as being prepared for a
* transaction on this specific binder object. Based on this, the format of the wire binder
* protocol may change. For future compatibility, it is recommended to use this for all
* Parcels.
*/
@NonNull
public static Parcel obtain(@NonNull IBinder binder) {
Parcel parcel = Parcel.obtain();
parcel.markForBinder(binder);
return parcel;
}
/**
* Put a Parcel object back into the pool. You must not touch
* the object after this call.
*/
public final void recycle() {
if (mRecycled) {
Log.wtf(TAG, "Recycle called on unowned Parcel. (recycle twice?) Here: "
+ Log.getStackTraceString(new Throwable())
+ " Original recycle call (if DEBUG_RECYCLE): ", mStack);
return;
}
mRecycled = true;
// We try to reset the entire object here, but in order to be
// able to print a stack when a Parcel is recycled twice, that
// is cleared in obtain instead.
mClassCookies = null;
freeBuffer();
if (mOwnsNativeParcelObject) {
synchronized (sPoolSync) {
if (sOwnedPoolSize < POOL_SIZE) {
mPoolNext = sOwnedPool;
sOwnedPool = this;
sOwnedPoolSize++;
}
}
} else {
mNativePtr = 0;
synchronized (sPoolSync) {
if (sHolderPoolSize < POOL_SIZE) {
mPoolNext = sHolderPool;
sHolderPool = this;
sHolderPoolSize++;
}
}
}
}
/**
* Set a {@link ReadWriteHelper}, which can be used to avoid having duplicate strings, for
* example.
*
* @hide
*/
public void setReadWriteHelper(@Nullable ReadWriteHelper helper) {
mReadWriteHelper = helper != null ? helper : ReadWriteHelper.DEFAULT;
}
/**
* @return whether this parcel has a {@link ReadWriteHelper}.
*
* @hide
*/
public boolean hasReadWriteHelper() {
return (mReadWriteHelper != null) && (mReadWriteHelper != ReadWriteHelper.DEFAULT);
}
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public static native long getGlobalAllocSize();
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public static native long getGlobalAllocCount();
/**
* Parcel data should be zero'd before realloc'd or deleted.
*
* Note: currently this feature requires multiple things to work in concert:
* - markSensitive must be called on every relative Parcel
* - FLAG_CLEAR_BUF must be passed into the kernel
* This requires having code which does the right thing in every method and in every backend
* of AIDL. Rather than exposing this API, it should be replaced with a single API on
* IBinder objects which can be called once, and the information should be fed into the
* Parcel using markForBinder APIs. In terms of code size and number of API calls, this is
* much more extensible.
*
* @hide
*/
public final void markSensitive() {
nativeMarkSensitive(mNativePtr);
}
/**
* @hide
*/
private void markForBinder(@NonNull IBinder binder) {
nativeMarkForBinder(mNativePtr, binder);
}
/**
* Whether this Parcel is written for an RPC transaction.
*
* @hide
*/
public final boolean isForRpc() {
return nativeIsForRpc(mNativePtr);
}
/** @hide */
@ParcelFlags
@TestApi
public int getFlags() {
return mFlags;
}
/** @hide */
public void setFlags(@ParcelFlags int flags) {
mFlags = flags;
}
/** @hide */
public void addFlags(@ParcelFlags int flags) {
mFlags |= flags;
}
/** @hide */
private boolean hasFlags(@ParcelFlags int flags) {
return (mFlags & flags) == flags;
}
/**
* This method is used by the AIDL compiler for system components. Not intended to be
* used by non-system apps.
*/
// Note: Ideally this method should be @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES),
// but we need to make this method public due to the way the aidl compiler is compiled.
// We don't really need to protect it; even if 3p / non-system apps, nothing would happen.
// This would only work when used on a reply parcel by a binder object that's allowed-blocking.
public void setPropagateAllowBlocking() {
addFlags(FLAG_PROPAGATE_ALLOW_BLOCKING);
}
/**
* Returns the total amount of data contained in the parcel.
*/
public int dataSize() {
return nativeDataSize(mNativePtr);
}
/**
* Returns the amount of data remaining to be read from the
* parcel. That is, {@link #dataSize}-{@link #dataPosition}.
*/
public final int dataAvail() {
return nativeDataAvail(mNativePtr);
}
/**
* Returns the current position in the parcel data. Never
* more than {@link #dataSize}.
*/
public final int dataPosition() {
return nativeDataPosition(mNativePtr);
}
/**
* Returns the total amount of space in the parcel. This is always
* >= {@link #dataSize}. The difference between it and dataSize() is the
* amount of room left until the parcel needs to re-allocate its
* data buffer.
*/
public final int dataCapacity() {
return nativeDataCapacity(mNativePtr);
}
/**
* Change the amount of data in the parcel. Can be either smaller or
* larger than the current size. If larger than the current capacity,
* more memory will be allocated.
*
* @param size The new number of bytes in the Parcel.
*/
public final void setDataSize(int size) {
nativeSetDataSize(mNativePtr, size);
}
/**
* Move the current read/write position in the parcel.
* @param pos New offset in the parcel; must be between 0 and
* {@link #dataSize}.
*/
public final void setDataPosition(int pos) {
nativeSetDataPosition(mNativePtr, pos);
}
/**
* Change the capacity (current available space) of the parcel.
*
* @param size The new capacity of the parcel, in bytes. Can not be
* less than {@link #dataSize} -- that is, you can not drop existing data
* with this method.
*/
public final void setDataCapacity(int size) {
nativeSetDataCapacity(mNativePtr, size);
}
/** @hide */
public final boolean pushAllowFds(boolean allowFds) {
return nativePushAllowFds(mNativePtr, allowFds);
}
/** @hide */
public final void restoreAllowFds(boolean lastValue) {
nativeRestoreAllowFds(mNativePtr, lastValue);
}
/**
* Returns the raw bytes of the parcel.
*
* <p class="note">The data you retrieve here <strong>must not</strong>
* be placed in any kind of persistent storage (on local disk, across
* a network, etc). For that, you should use standard serialization
* or another kind of general serialization mechanism. The Parcel
* marshalled representation is highly optimized for local IPC, and as
* such does not attempt to maintain compatibility with data created
* in different versions of the platform.
*/
public final byte[] marshall() {
return nativeMarshall(mNativePtr);
}
/**
* Fills the raw bytes of this Parcel with the supplied data.
*/
public final void unmarshall(@NonNull byte[] data, int offset, int length) {
nativeUnmarshall(mNativePtr, data, offset, length);
}
public final void appendFrom(Parcel parcel, int offset, int length) {
nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length);
}
/** @hide */
public int compareData(Parcel other) {
return nativeCompareData(mNativePtr, other.mNativePtr);
}
/** @hide */
public static boolean compareData(Parcel a, int offsetA, Parcel b, int offsetB, int length) {
return nativeCompareDataInRange(a.mNativePtr, offsetA, b.mNativePtr, offsetB, length);
}
/** @hide */
public final void setClassCookie(Class clz, Object cookie) {
if (mClassCookies == null) {
mClassCookies = new ArrayMap<>();
}
mClassCookies.put(clz, cookie);
}
/** @hide */
@Nullable
public final Object getClassCookie(Class clz) {
return mClassCookies != null ? mClassCookies.get(clz) : null;
}
/** @hide */
public final void adoptClassCookies(Parcel from) {
mClassCookies = from.mClassCookies;
}
/** @hide */
public Map<Class, Object> copyClassCookies() {
return new ArrayMap<>(mClassCookies);
}
/** @hide */
public void putClassCookies(Map<Class, Object> cookies) {
if (cookies == null) {
return;
}
if (mClassCookies == null) {
mClassCookies = new ArrayMap<>();
}
mClassCookies.putAll(cookies);
}
/**
* Report whether the parcel contains any marshalled file descriptors.
*/
public boolean hasFileDescriptors() {
return nativeHasFileDescriptors(mNativePtr);
}
/**
* Report whether the parcel contains any marshalled file descriptors in the range defined by
* {@code offset} and {@code length}.
*
* @param offset The offset from which the range starts. Should be between 0 and
* {@link #dataSize()}.
* @param length The length of the range. Should be between 0 and {@link #dataSize()} - {@code
* offset}.
* @return whether there are file descriptors or not.
* @throws IllegalArgumentException if the parameters are out of the permitted ranges.
*/
public boolean hasFileDescriptors(int offset, int length) {
return nativeHasFileDescriptorsInRange(mNativePtr, offset, length);
}
/**
* Check if the object has file descriptors.
*
* <p>Objects supported are {@link Parcel} and objects that can be passed to {@link
* #writeValue(Object)}}
*
* <p>For most cases, it will use the self-reported {@link Parcelable#describeContents()} method
* for that.
*
* @throws IllegalArgumentException if you provide any object not supported by above methods
* (including if the unsupported object is inside a nested container).
*
* @hide
*/
public static boolean hasFileDescriptors(Object value) {
if (value instanceof Parcel) {
Parcel parcel = (Parcel) value;
if (parcel.hasFileDescriptors()) {
return true;
}
} else if (value instanceof LazyValue) {
LazyValue lazy = (LazyValue) value;
if (lazy.hasFileDescriptors()) {
return true;
}
} else if (value instanceof Parcelable) {
Parcelable parcelable = (Parcelable) value;
if ((parcelable.describeContents() & Parcelable.CONTENTS_FILE_DESCRIPTOR) != 0) {
return true;
}
} else if (value instanceof ArrayMap<?, ?>) {
ArrayMap<?, ?> map = (ArrayMap<?, ?>) value;
for (int i = 0, n = map.size(); i < n; i++) {
if (hasFileDescriptors(map.keyAt(i))
|| hasFileDescriptors(map.valueAt(i))) {
return true;
}
}
} else if (value instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) value;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (hasFileDescriptors(entry.getKey())
|| hasFileDescriptors(entry.getValue())) {
return true;
}
}
} else if (value instanceof List<?>) {
List<?> list = (List<?>) value;
for (int i = 0, n = list.size(); i < n; i++) {
if (hasFileDescriptors(list.get(i))) {
return true;
}
}
} else if (value instanceof SparseArray<?>) {
SparseArray<?> array = (SparseArray<?>) value;
for (int i = 0, n = array.size(); i < n; i++) {
if (hasFileDescriptors(array.valueAt(i))) {
return true;
}
}
} else if (value instanceof Object[]) {
Object[] array = (Object[]) value;
for (int i = 0, n = array.length; i < n; i++) {
if (hasFileDescriptors(array[i])) {
return true;
}
}
} else {
getValueType(value); // Will throw if value is not supported
}
return false;
}
/**
* Store or read an IBinder interface token in the parcel at the current
* {@link #dataPosition}. This is used to validate that the marshalled
* transaction is intended for the target interface. This is typically written
* at the beginning of transactions as a header.
*/
public final void writeInterfaceToken(@NonNull String interfaceName) {
nativeWriteInterfaceToken(mNativePtr, interfaceName);
}
/**
* Read the header written by writeInterfaceToken and verify it matches
* the interface name in question. If the wrong interface type is present,
* {@link SecurityException} is thrown. When used over binder, this exception
* should propagate to the caller.
*/
public final void enforceInterface(@NonNull String interfaceName) {
nativeEnforceInterface(mNativePtr, interfaceName);
}
/**
* Verify there are no bytes left to be read on the Parcel.
*
* @throws BadParcelableException If the current position hasn't reached the end of the Parcel.
* When used over binder, this exception should propagate to the caller.
*/
public void enforceNoDataAvail() {
final int n = dataAvail();
if (n > 0) {
throw new BadParcelableException("Parcel data not fully consumed, unread size: " + n);
}
}
/**
* Writes the work source uid to the request headers.
*
* <p>It requires the headers to have been written/read already to replace the work source.
*
* @return true if the request headers have been updated.
*
* @hide
*/
public boolean replaceCallingWorkSourceUid(int workSourceUid) {
return nativeReplaceCallingWorkSourceUid(mNativePtr, workSourceUid);
}
/**
* Reads the work source uid from the request headers.
*
* <p>Unlike other read methods, this method does not read the parcel at the current
* {@link #dataPosition}. It will set the {@link #dataPosition} before the read and restore the
* position after reading the request header.
*
* @return the work source uid or {@link Binder#UNSET_WORKSOURCE} if headers have not been
* written/parsed yet.
*
* @hide
*/
public int readCallingWorkSourceUid() {
return nativeReadCallingWorkSourceUid(mNativePtr);
}
/**
* Write a byte array into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
* @param b Bytes to place into the parcel.
*/
public final void writeByteArray(@Nullable byte[] b) {
writeByteArray(b, 0, (b != null) ? b.length : 0);
}
/**
* Write a byte array into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
* @param b Bytes to place into the parcel.
* @param offset Index of first byte to be written.
* @param len Number of bytes to write.
*/
public final void writeByteArray(@Nullable byte[] b, int offset, int len) {
if (b == null) {
writeInt(-1);
return;
}
ArrayUtils.throwsIfOutOfBounds(b.length, offset, len);
nativeWriteByteArray(mNativePtr, b, offset, len);
}
/**
* Write a blob of data into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
*
* <p> If the blob is small, then it is stored in-place, otherwise it is transferred by way of
* an anonymous shared memory region. If you prefer send in-place, please use
* {@link #writeByteArray(byte[])}.
*
* @param b Bytes to place into the parcel.
*
* @see #readBlob()
*/
public final void writeBlob(@Nullable byte[] b) {
writeBlob(b, 0, (b != null) ? b.length : 0);
}
/**
* Write a blob of data into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
*
* <p> If the blob is small, then it is stored in-place, otherwise it is transferred by way of
* an anonymous shared memory region. If you prefer send in-place, please use
* {@link #writeByteArray(byte[], int, int)}.
*
* @param b Bytes to place into the parcel.
* @param offset Index of first byte to be written.
* @param len Number of bytes to write.
*
* @see #readBlob()
*/
public final void writeBlob(@Nullable byte[] b, int offset, int len) {
if (b == null) {
writeInt(-1);
return;
}
ArrayUtils.throwsIfOutOfBounds(b.length, offset, len);
nativeWriteBlob(mNativePtr, b, offset, len);
}
// The OK status from system/core/libutils/include/utils/Errors.h .
// We shall pass all other error codes back to native for throwing exceptions. The error
// check is done in Java to allow using @CriticalNative calls for the success path.
private static final int OK = 0;
/**
* Write an integer value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeInt(int val) {
int err = nativeWriteInt(mNativePtr, val);
if (err != OK) {
nativeSignalExceptionForError(err);
}
}
/**
* Write a long integer value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeLong(long val) {
int err = nativeWriteLong(mNativePtr, val);
if (err != OK) {
nativeSignalExceptionForError(err);
}
}
/**
* Write a floating point value into the parcel at the current
* dataPosition(), growing dataCapacity() if needed.
*/
public final void writeFloat(float val) {
int err = nativeWriteFloat(mNativePtr, val);
if (err != OK) {
nativeSignalExceptionForError(err);
}
}
/**
* Write a double precision floating point value into the parcel at the
* current dataPosition(), growing dataCapacity() if needed.
*/
public final void writeDouble(double val) {
int err = nativeWriteDouble(mNativePtr, val);
if (err != OK) {
nativeSignalExceptionForError(err);
}
}
/**
* Write a string value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeString(@Nullable String val) {
writeString16(val);
}
/** {@hide} */
public final void writeString8(@Nullable String val) {
mReadWriteHelper.writeString8(this, val);
}
/** {@hide} */
public final void writeString16(@Nullable String val) {
mReadWriteHelper.writeString16(this, val);
}
/**
* Write a string without going though a {@link ReadWriteHelper}. Subclasses of
* {@link ReadWriteHelper} must use this method instead of {@link #writeString} to avoid
* infinity recursive calls.
*
* @hide
*/
public void writeStringNoHelper(@Nullable String val) {
writeString16NoHelper(val);
}
/** {@hide} */
public void writeString8NoHelper(@Nullable String val) {
nativeWriteString8(mNativePtr, val);
}
/** {@hide} */
public void writeString16NoHelper(@Nullable String val) {
nativeWriteString16(mNativePtr, val);
}
/**
* Write a boolean value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*
* <p>Note: This method currently delegates to writeInt with a value of 1 or 0
* for true or false, respectively, but may change in the future.
*/
public final void writeBoolean(boolean val) {
writeInt(val ? 1 : 0);
}
/**
* Write a CharSequence value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
* @hide
*/
@UnsupportedAppUsage
public final void writeCharSequence(@Nullable CharSequence val) {
TextUtils.writeToParcel(val, this, 0);
}
/**
* Write an object into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeStrongBinder(IBinder val) {
nativeWriteStrongBinder(mNativePtr, val);
}
/**
* Write an object into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeStrongInterface(IInterface val) {
writeStrongBinder(val == null ? null : val.asBinder());
}
/**
* Write a FileDescriptor into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*
* <p class="caution">The file descriptor will not be closed, which may
* result in file descriptor leaks when objects are returned from Binder
* calls. Use {@link ParcelFileDescriptor#writeToParcel} instead, which
* accepts contextual flags and will close the original file descriptor
* if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
*/
public final void writeFileDescriptor(@NonNull FileDescriptor val) {
nativeWriteFileDescriptor(mNativePtr, val);
}
/**
* {@hide}
* This will be the new name for writeFileDescriptor, for consistency.
**/
public final void writeRawFileDescriptor(@NonNull FileDescriptor val) {
nativeWriteFileDescriptor(mNativePtr, val);
}
/**
* {@hide}
* Write an array of FileDescriptor objects into the Parcel.
*
* @param value The array of objects to be written.
*/
public final void writeRawFileDescriptorArray(@Nullable FileDescriptor[] value) {
if (value != null) {
int N = value.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeRawFileDescriptor(value[i]);
}
} else {
writeInt(-1);
}
}
/**
* Write a byte value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*
* <p>Note: This method currently delegates to writeInt but may change in
* the future.
*/
public final void writeByte(byte val) {
writeInt(val);
}
/**
* Please use {@link #writeBundle} instead. Flattens a Map into the parcel
* at the current dataPosition(),
* growing dataCapacity() if needed. The Map keys must be String objects.
* The Map values are written using {@link #writeValue} and must follow
* the specification there.
*
* <p>It is strongly recommended to use {@link #writeBundle} instead of
* this method, since the Bundle class provides a type-safe API that
* allows you to avoid mysterious type errors at the point of marshalling.
*/
public final void writeMap(@Nullable Map val) {
writeMapInternal((Map<String, Object>) val);
}
/**
* Flatten a Map into the parcel at the current dataPosition(),
* growing dataCapacity() if needed. The Map keys must be String objects.
*/
/* package */ void writeMapInternal(@Nullable Map<String,Object> val) {
if (val == null) {
writeInt(-1);
return;
}
Set<Map.Entry<String,Object>> entries = val.entrySet();
int size = entries.size();
writeInt(size);
for (Map.Entry<String,Object> e : entries) {
writeValue(e.getKey());
writeValue(e.getValue());
size--;
}
if (size != 0) {
throw new BadParcelableException("Map size does not match number of entries!");
}
}
/**
* Flatten an ArrayMap into the parcel at the current dataPosition(),
* growing dataCapacity() if needed. The Map keys must be String objects.
*/
/* package */ void writeArrayMapInternal(@Nullable ArrayMap<String, Object> val) {
if (val == null) {
writeInt(-1);
return;
}
// Keep the format of this Parcel in sync with writeToParcelInner() in
// frameworks/native/libs/binder/PersistableBundle.cpp.
final int N = val.size();
writeInt(N);
if (DEBUG_ARRAY_MAP) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
}
int startPos;
for (int i=0; i<N; i++) {
if (DEBUG_ARRAY_MAP) startPos = dataPosition();
writeString(val.keyAt(i));
writeValue(val.valueAt(i));
if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
+ (dataPosition()-startPos) + " bytes: key=0x"
+ Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
+ " " + val.keyAt(i));
}
}
/**
* @hide For testing only.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void writeArrayMap(@Nullable ArrayMap<String, Object> val) {
writeArrayMapInternal(val);
}
/**
* Flatten an {@link ArrayMap} with string keys containing a particular object
* type into the parcel at the current dataPosition() and growing dataCapacity()
* if needed. The type of the objects in the array must be one that implements
* Parcelable. Only the raw data of the objects is written and not their type,
* so you must use the corresponding {@link #createTypedArrayMap(Parcelable.Creator)}
*
* @param val The map of objects to be written.
* @param parcelableFlags The parcelable flags to use.
*
* @see #createTypedArrayMap(Parcelable.Creator)
* @see Parcelable
*/
public <T extends Parcelable> void writeTypedArrayMap(@Nullable ArrayMap<String, T> val,
int parcelableFlags) {
if (val == null) {
writeInt(-1);
return;
}
final int count = val.size();
writeInt(count);
for (int i = 0; i < count; i++) {
writeString(val.keyAt(i));
writeTypedObject(val.valueAt(i), parcelableFlags);
}
}
/**
* Write an array set to the parcel.
*
* @param val The array set to write.
*
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
final int size = (val != null) ? val.size() : -1;
writeInt(size);
for (int i = 0; i < size; i++) {
writeValue(val.valueAt(i));
}
}
/**
* Flatten a Bundle into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeBundle(@Nullable Bundle val) {
if (val == null) {
writeInt(-1);
return;
}
val.writeToParcel(this, 0);
}
/**
* Flatten a PersistableBundle into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writePersistableBundle(@Nullable PersistableBundle val) {
if (val == null) {
writeInt(-1);
return;
}
val.writeToParcel(this, 0);
}
/**
* Flatten a Size into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeSize(@NonNull Size val) {
writeInt(val.getWidth());
writeInt(val.getHeight());
}
/**
* Flatten a SizeF into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeSizeF(@NonNull SizeF val) {
writeFloat(val.getWidth());
writeFloat(val.getHeight());
}
/**
* Flatten a List into the parcel at the current dataPosition(), growing
* dataCapacity() if needed. The List values are written using
* {@link #writeValue} and must follow the specification there.
*/
public final void writeList(@Nullable List val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeValue(val.get(i));
i++;
}
}
/**
* Flatten an Object array into the parcel at the current dataPosition(),
* growing dataCapacity() if needed. The array values are written using
* {@link #writeValue} and must follow the specification there.
*/
public final void writeArray(@Nullable Object[] val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.length;
int i=0;
writeInt(N);
while (i < N) {
writeValue(val[i]);
i++;
}
}
/**
* Flatten a generic SparseArray into the parcel at the current
* dataPosition(), growing dataCapacity() if needed. The SparseArray
* values are written using {@link #writeValue} and must follow the
* specification there.
*/
public final <T> void writeSparseArray(@Nullable SparseArray<T> val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
writeInt(N);
int i=0;
while (i < N) {
writeInt(val.keyAt(i));
writeValue(val.valueAt(i));
i++;
}
}
public final void writeSparseBooleanArray(@Nullable SparseBooleanArray val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
writeInt(N);
int i=0;
while (i < N) {
writeInt(val.keyAt(i));
writeByte((byte)(val.valueAt(i) ? 1 : 0));
i++;
}
}
/**
* @hide
*/
public final void writeSparseIntArray(@Nullable SparseIntArray val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
writeInt(N);
int i=0;
while (i < N) {
writeInt(val.keyAt(i));
writeInt(val.valueAt(i));
i++;
}
}
public final void writeBooleanArray(@Nullable boolean[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeInt(val[i] ? 1 : 0);
}
} else {
writeInt(-1);
}
}
@Nullable
public final boolean[] createBooleanArray() {
int N = readInt();
// >>2 as a fast divide-by-4 works in the create*Array() functions
// because dataAvail() will never return a negative number. 4 is
// the size of a stored boolean in the stream.
if (N >= 0 && N <= (dataAvail() >> 2)) {
boolean[] val = new boolean[N];
for (int i=0; i<N; i++) {
val[i] = readInt() != 0;
}
return val;
} else {
return null;
}
}
public final void readBooleanArray(@NonNull boolean[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readInt() != 0;
}
} else {
throw new RuntimeException("bad array lengths");
}
}
/** @hide */
public void writeShortArray(@Nullable short[] val) {
if (val != null) {
int n = val.length;
writeInt(n);
for (int i = 0; i < n; i++) {
writeInt(val[i]);
}
} else {
writeInt(-1);
}
}
/** @hide */
@Nullable
public short[] createShortArray() {
int n = readInt();
if (n >= 0 && n <= (dataAvail() >> 2)) {
short[] val = new short[n];
for (int i = 0; i < n; i++) {
val[i] = (short) readInt();
}
return val;
} else {
return null;
}
}
/** @hide */
public void readShortArray(@NonNull short[] val) {
int n = readInt();
if (n == val.length) {
for (int i = 0; i < n; i++) {
val[i] = (short) readInt();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeCharArray(@Nullable char[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeInt((int)val[i]);
}
} else {
writeInt(-1);
}
}
@Nullable
public final char[] createCharArray() {
int N = readInt();
if (N >= 0 && N <= (dataAvail() >> 2)) {
char[] val = new char[N];
for (int i=0; i<N; i++) {
val[i] = (char)readInt();
}
return val;
} else {
return null;
}
}
public final void readCharArray(@NonNull char[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = (char)readInt();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeIntArray(@Nullable int[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeInt(val[i]);
}
} else {
writeInt(-1);
}
}
@Nullable
public final int[] createIntArray() {
int N = readInt();
if (N >= 0 && N <= (dataAvail() >> 2)) {
int[] val = new int[N];
for (int i=0; i<N; i++) {
val[i] = readInt();
}
return val;
} else {
return null;
}
}
public final void readIntArray(@NonNull int[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readInt();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeLongArray(@Nullable long[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeLong(val[i]);
}
} else {
writeInt(-1);
}
}
@Nullable
public final long[] createLongArray() {
int N = readInt();
// >>3 because stored longs are 64 bits
if (N >= 0 && N <= (dataAvail() >> 3)) {
long[] val = new long[N];
for (int i=0; i<N; i++) {
val[i] = readLong();
}
return val;
} else {
return null;
}
}
public final void readLongArray(@NonNull long[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readLong();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeFloatArray(@Nullable float[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeFloat(val[i]);
}
} else {
writeInt(-1);
}
}
@Nullable
public final float[] createFloatArray() {
int N = readInt();
// >>2 because stored floats are 4 bytes
if (N >= 0 && N <= (dataAvail() >> 2)) {
float[] val = new float[N];
for (int i=0; i<N; i++) {
val[i] = readFloat();
}
return val;
} else {
return null;
}
}
public final void readFloatArray(@NonNull float[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readFloat();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeDoubleArray(@Nullable double[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeDouble(val[i]);
}
} else {
writeInt(-1);
}
}
@Nullable
public final double[] createDoubleArray() {
int N = readInt();
// >>3 because stored doubles are 8 bytes
if (N >= 0 && N <= (dataAvail() >> 3)) {
double[] val = new double[N];
for (int i=0; i<N; i++) {
val[i] = readDouble();
}
return val;
} else {
return null;
}
}
public final void readDoubleArray(@NonNull double[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readDouble();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeStringArray(@Nullable String[] val) {
writeString16Array(val);
}
@Nullable
public final String[] createStringArray() {
return createString16Array();
}
public final void readStringArray(@NonNull String[] val) {
readString16Array(val);
}
/** {@hide} */
public final void writeString8Array(@Nullable String[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeString8(val[i]);
}
} else {
writeInt(-1);
}
}
/** {@hide} */
@Nullable
public final String[] createString8Array() {
int N = readInt();
if (N >= 0) {
String[] val = new String[N];
for (int i=0; i<N; i++) {
val[i] = readString8();
}
return val;
} else {
return null;
}
}
/** {@hide} */
public final void readString8Array(@NonNull String[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readString8();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
/** {@hide} */
public final void writeString16Array(@Nullable String[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeString16(val[i]);
}
} else {
writeInt(-1);
}
}
/** {@hide} */
@Nullable
public final String[] createString16Array() {
int N = readInt();
if (N >= 0) {
String[] val = new String[N];
for (int i=0; i<N; i++) {
val[i] = readString16();
}
return val;
} else {
return null;
}
}
/** {@hide} */
public final void readString16Array(@NonNull String[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readString16();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
public final void writeBinderArray(@Nullable IBinder[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeStrongBinder(val[i]);
}
} else {
writeInt(-1);
}
}
/**
* Flatten a homogeneous array containing an IInterface type into the parcel,
* at the current dataPosition() and growing dataCapacity() if needed. The
* type of the objects in the array must be one that implements IInterface.
*
* @param val The array of objects to be written.
*
* @see #createInterfaceArray
* @see #readInterfaceArray
* @see IInterface
*/
public final <T extends IInterface> void writeInterfaceArray(
@SuppressLint("ArrayReturn") @Nullable T[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeStrongInterface(val[i]);
}
} else {
writeInt(-1);
}
}
/**
* @hide
*/
public final void writeCharSequenceArray(@Nullable CharSequence[] val) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeCharSequence(val[i]);
}
} else {
writeInt(-1);
}
}
/**
* @hide
*/
public final void writeCharSequenceList(@Nullable ArrayList<CharSequence> val) {
if (val != null) {
int N = val.size();
writeInt(N);
for (int i=0; i<N; i++) {
writeCharSequence(val.get(i));
}
} else {
writeInt(-1);
}
}
@Nullable
public final IBinder[] createBinderArray() {
int N = readInt();
if (N >= 0) {
IBinder[] val = new IBinder[N];
for (int i=0; i<N; i++) {
val[i] = readStrongBinder();
}
return val;
} else {
return null;
}
}
public final void readBinderArray(@NonNull IBinder[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readStrongBinder();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
/**
* Read and return a new array of T (IInterface) from the parcel.
*
* @return the IInterface array of type T
* @param newArray a function to create an array of T with a given length
* @param asInterface a function to convert IBinder object into T (IInterface)
*/
@SuppressLint({"ArrayReturn", "NullableCollection", "SamShouldBeLast"})
@Nullable
public final <T extends IInterface> T[] createInterfaceArray(
@NonNull IntFunction<T[]> newArray, @NonNull Function<IBinder, T> asInterface) {
int N = readInt();
if (N >= 0) {
T[] val = newArray.apply(N);
for (int i=0; i<N; i++) {
val[i] = asInterface.apply(readStrongBinder());
}
return val;
} else {
return null;
}
}
/**
* Read an array of T (IInterface) from a parcel.
*
* @param asInterface a function to convert IBinder object into T (IInterface)
*
* @throws BadParcelableException Throws BadParcelableException if the length of `val`
* mismatches the number of items in the parcel.
*/
public final <T extends IInterface> void readInterfaceArray(
@SuppressLint("ArrayReturn") @NonNull T[] val,
@NonNull Function<IBinder, T> asInterface) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = asInterface.apply(readStrongBinder());
}
} else {
throw new BadParcelableException("bad array lengths");
}
}
/**
* Flatten a List containing a particular object type into the parcel, at
* the current dataPosition() and growing dataCapacity() if needed. The
* type of the objects in the list must be one that implements Parcelable.
* Unlike the generic writeList() method, however, only the raw data of the
* objects is written and not their type, so you must use the corresponding
* readTypedList() to unmarshall them.
*
* @param val The list of objects to be written.
*
* @see #createTypedArrayList
* @see #readTypedList
* @see Parcelable
*/
public final <T extends Parcelable> void writeTypedList(@Nullable List<T> val) {
writeTypedList(val, 0);
}
/**
* Flatten a {@link SparseArray} containing a particular object type into the parcel
* at the current dataPosition() and growing dataCapacity() if needed. The
* type of the objects in the array must be one that implements Parcelable.
* Unlike the generic {@link #writeSparseArray(SparseArray)} method, however, only
* the raw data of the objects is written and not their type, so you must use the
* corresponding {@link #createTypedSparseArray(Parcelable.Creator)}.
*
* @param val The list of objects to be written.
* @param parcelableFlags The parcelable flags to use.
*
* @see #createTypedSparseArray(Parcelable.Creator)
* @see Parcelable
*/
public final <T extends Parcelable> void writeTypedSparseArray(@Nullable SparseArray<T> val,
int parcelableFlags) {
if (val == null) {
writeInt(-1);
return;
}
final int count = val.size();
writeInt(count);
for (int i = 0; i < count; i++) {
writeInt(val.keyAt(i));
writeTypedObject(val.valueAt(i), parcelableFlags);
}
}
/**
* Flatten a List containing a particular object type into the parcel, at
* the current dataPosition() and growing dataCapacity() if needed. The
* type of the objects in the list must be one that implements Parcelable.
* Unlike the generic writeList() method, however, only the raw data of the
* objects is written and not their type, so you must use the corresponding
* readTypedList() to unmarshall them.
*
* @param val The list of objects to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
*
* @see #createTypedArrayList
* @see #readTypedList
* @see Parcelable
*/
public <T extends Parcelable> void writeTypedList(@Nullable List<T> val, int parcelableFlags) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeTypedObject(val.get(i), parcelableFlags);
i++;
}
}
/**
* Flatten a List containing String objects into the parcel, at
* the current dataPosition() and growing dataCapacity() if needed. They
* can later be retrieved with {@link #createStringArrayList} or
* {@link #readStringList}.
*
* @param val The list of strings to be written.
*
* @see #createStringArrayList
* @see #readStringList
*/
public final void writeStringList(@Nullable List<String> val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeString(val.get(i));
i++;
}
}
/**
* Flatten a List containing IBinder objects into the parcel, at
* the current dataPosition() and growing dataCapacity() if needed. They
* can later be retrieved with {@link #createBinderArrayList} or
* {@link #readBinderList}.
*
* @param val The list of strings to be written.
*
* @see #createBinderArrayList
* @see #readBinderList
*/
public final void writeBinderList(@Nullable List<IBinder> val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeStrongBinder(val.get(i));
i++;
}
}
/**
* Flatten a {@code List} containing T (IInterface) objects into this parcel
* at the current position. They can later be retrieved with
* {@link #createInterfaceArrayList} or {@link #readInterfaceList}.
*
* @see #createInterfaceArrayList
* @see #readInterfaceList
*/
public final <T extends IInterface> void writeInterfaceList(@Nullable List<T> val) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeStrongInterface(val.get(i));
i++;
}
}
/**
* Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
* at the current position. They can later be retrieved using
* {@link #readParcelableList(List, ClassLoader)} if required.
*
* @see #readParcelableList(List, ClassLoader)
*/
public final <T extends Parcelable> void writeParcelableList(@Nullable List<T> val, int flags) {
if (val == null) {
writeInt(-1);
return;
}
int N = val.size();
int i=0;
writeInt(N);
while (i < N) {
writeParcelable(val.get(i), flags);
i++;
}
}
/**
* Flatten a homogeneous array containing a particular object type into
* the parcel, at
* the current dataPosition() and growing dataCapacity() if needed. The
* type of the objects in the array must be one that implements Parcelable.
* Unlike the {@link #writeParcelableArray} method, however, only the
* raw data of the objects is written and not their type, so you must use
* {@link #readTypedArray} with the correct corresponding
* {@link Parcelable.Creator} implementation to unmarshall them.
*
* @param val The array of objects to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
*
* @see #readTypedArray
* @see #writeParcelableArray
* @see Parcelable.Creator
*/
public final <T extends Parcelable> void writeTypedArray(@Nullable T[] val,
int parcelableFlags) {
if (val != null) {
int N = val.length;
writeInt(N);
for (int i = 0; i < N; i++) {
writeTypedObject(val[i], parcelableFlags);
}
} else {
writeInt(-1);
}
}
/**
* Flatten the Parcelable object into the parcel.
*
* @param val The Parcelable object to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
*
* @see #readTypedObject
*/
public final <T extends Parcelable> void writeTypedObject(@Nullable T val,
int parcelableFlags) {
if (val != null) {
writeInt(1);
val.writeToParcel(this, parcelableFlags);
} else {
writeInt(0);
}
}
/**
* Flatten a homogeneous multi-dimensional array with fixed-size. This delegates to other
* APIs to write a one-dimensional array. Use {@link #readFixedArray(Object)} or
* {@link #createFixedArray(Class, int[])} with the same dimensions to unmarshal.
*
* @param val The array to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
* Used only if val is an array of Parcelable objects.
* @param dimensions an array of int representing length of each dimension. The array should be
* sized with the exact size of dimensions.
*
* @see #readFixedArray
* @see #createFixedArray createFixedArray(Class<T>, Parcelable.Creator<S>, int...)
* @see #writeBooleanArray
* @see #writeByteArray
* @see #writeCharArray
* @see #writeIntArray
* @see #writeLongArray
* @see #writeFloatArray
* @see #writeDoubleArray
* @see #writeBinderArray
* @see #writeInterfaceArray
* @see #writeTypedArray
* @throws BadParcelableException If the array's component type is not supported or if its
* size doesn't match with the given dimensions.
*/
public <T> void writeFixedArray(@Nullable T val, int parcelableFlags,
@NonNull int... dimensions) {
if (val == null) {
writeInt(-1);
return;
}
writeFixedArrayInternal(val, parcelableFlags, /*index=*/0, dimensions);
}
private <T> void writeFixedArrayInternal(T val, int parcelableFlags, int index,
int[] dimensions) {
if (index >= dimensions.length) {
throw new BadParcelableException("Array has more dimensions than expected: "
+ dimensions.length);
}
int length = dimensions[index];
// val should be an array of length N
if (val == null) {
throw new BadParcelableException("Non-null array shouldn't have a null array.");
}
if (!val.getClass().isArray()) {
throw new BadParcelableException("Not an array: " + val);
}
if (Array.getLength(val) != length) {
throw new BadParcelableException("bad length: expected " + length + ", but got "
+ Array.getLength(val));
}
// Delegates to other writers if this is a one-dimensional array.
// Otherwise, write component arrays with recursive calls.
final Class<?> componentType = val.getClass().getComponentType();
if (!componentType.isArray() && index + 1 != dimensions.length) {
throw new BadParcelableException("Array has fewer dimensions than expected: "
+ dimensions.length);
}
if (componentType == boolean.class) {
writeBooleanArray((boolean[]) val);
} else if (componentType == byte.class) {
writeByteArray((byte[]) val);
} else if (componentType == char.class) {
writeCharArray((char[]) val);
} else if (componentType == int.class) {
writeIntArray((int[]) val);
} else if (componentType == long.class) {
writeLongArray((long[]) val);
} else if (componentType == float.class) {
writeFloatArray((float[]) val);
} else if (componentType == double.class) {
writeDoubleArray((double[]) val);
} else if (componentType == IBinder.class) {
writeBinderArray((IBinder[]) val);
} else if (IInterface.class.isAssignableFrom(componentType)) {
writeInterfaceArray((IInterface[]) val);
} else if (Parcelable.class.isAssignableFrom(componentType)) {
writeTypedArray((Parcelable[]) val, parcelableFlags);
} else if (componentType.isArray()) {
writeInt(length);
for (int i = 0; i < length; i++) {
writeFixedArrayInternal(Array.get(val, i), parcelableFlags, index + 1,
dimensions);
}
} else {
throw new BadParcelableException("unknown type for fixed-size array: " + componentType);
}
}
/**
* Flatten a generic object in to a parcel. The given Object value may
* currently be one of the following types:
*
* <ul>
* <li> null
* <li> String
* <li> Byte
* <li> Short
* <li> Integer
* <li> Long
* <li> Float
* <li> Double
* <li> Boolean
* <li> String[]
* <li> boolean[]
* <li> byte[]
* <li> int[]
* <li> long[]
* <li> Object[] (supporting objects of the same type defined here).
* <li> {@link Bundle}
* <li> Map (as supported by {@link #writeMap}).
* <li> Any object that implements the {@link Parcelable} protocol.
* <li> Parcelable[]
* <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
* <li> List (as supported by {@link #writeList}).
* <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
* <li> {@link IBinder}
* <li> Any object that implements Serializable (but see
* {@link #writeSerializable} for caveats). Note that all of the
* previous types have relatively efficient implementations for
* writing to a Parcel; having to rely on the generic serialization
* approach is much less efficient and should be avoided whenever
* possible.
* </ul>
*
* <p class="caution">{@link Parcelable} objects are written with
* {@link Parcelable#writeToParcel} using contextual flags of 0. When
* serializing objects containing {@link ParcelFileDescriptor}s,
* this may result in file descriptor leaks when they are returned from
* Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
* should be used).</p>
*/
public final void writeValue(@Nullable Object v) {
if (v instanceof LazyValue) {
LazyValue value = (LazyValue) v;
value.writeToParcel(this);
return;
}
int type = getValueType(v);
writeInt(type);
if (isLengthPrefixed(type)) {
// Length
int length = dataPosition();
writeInt(-1); // Placeholder
// Object
int start = dataPosition();
writeValue(type, v);
int end = dataPosition();
// Backpatch length
setDataPosition(length);
writeInt(end - start);
setDataPosition(end);
} else {
writeValue(type, v);
}
}
/** @hide */
public static int getValueType(@Nullable Object v) {
if (v == null) {
return VAL_NULL;
} else if (v instanceof String) {
return VAL_STRING;
} else if (v instanceof Integer) {
return VAL_INTEGER;
} else if (v instanceof Map) {
return VAL_MAP;
} else if (v instanceof Bundle) {
// Must be before Parcelable
return VAL_BUNDLE;
} else if (v instanceof PersistableBundle) {
// Must be before Parcelable
return VAL_PERSISTABLEBUNDLE;
} else if (v instanceof SizeF) {
// Must be before Parcelable
return VAL_SIZEF;
} else if (v instanceof Parcelable) {
// IMPOTANT: cases for classes that implement Parcelable must
// come before the Parcelable case, so that their speci fic VAL_*
// types will be written.
return VAL_PARCELABLE;
} else if (v instanceof Short) {
return VAL_SHORT;
} else if (v instanceof Long) {
return VAL_LONG;
} else if (v instanceof Float) {
return VAL_FLOAT;
} else if (v instanceof Double) {
return VAL_DOUBLE;
} else if (v instanceof Boolean) {
return VAL_BOOLEAN;
} else if (v instanceof CharSequence) {
// Must be after String
return VAL_CHARSEQUENCE;
} else if (v instanceof List) {
return VAL_LIST;
} else if (v instanceof SparseArray) {
return VAL_SPARSEARRAY;
} else if (v instanceof boolean[]) {
return VAL_BOOLEANARRAY;
} else if (v instanceof byte[]) {
return VAL_BYTEARRAY;
} else if (v instanceof String[]) {
return VAL_STRINGARRAY;
} else if (v instanceof CharSequence[]) {
// Must be after String[] and before Object[]
return VAL_CHARSEQUENCEARRAY;
} else if (v instanceof IBinder) {
return VAL_IBINDER;
} else if (v instanceof Parcelable[]) {
return VAL_PARCELABLEARRAY;
} else if (v instanceof int[]) {
return VAL_INTARRAY;
} else if (v instanceof long[]) {
return VAL_LONGARRAY;
} else if (v instanceof Byte) {
return VAL_BYTE;
} else if (v instanceof Size) {
return VAL_SIZE;
} else if (v instanceof double[]) {
return VAL_DOUBLEARRAY;
} else if (v instanceof Character) {
return VAL_CHAR;
} else if (v instanceof short[]) {
return VAL_SHORTARRAY;
} else if (v instanceof char[]) {
return VAL_CHARARRAY;
} else if (v instanceof float[]) {
return VAL_FLOATARRAY;
} else {
Class<?> clazz = v.getClass();
if (clazz.isArray() && clazz.getComponentType() == Object.class) {
// Only pure Object[] are written here, Other arrays of non-primitive types are
// handled by serialization as this does not record the component type.
return VAL_OBJECTARRAY;
} else if (v instanceof Serializable) {
// Must be last
return VAL_SERIALIZABLE;
} else {
throw new IllegalArgumentException("Parcel: unknown type for value " + v);
}
}
}
/**
* Writes value {@code v} in the parcel. This does NOT write the int representing the type
* first.
*
* @hide
*/
public void writeValue(int type, @Nullable Object v) {
switch (type) {
case VAL_NULL:
break;
case VAL_STRING:
writeString((String) v);
break;
case VAL_INTEGER:
writeInt((Integer) v);
break;
case VAL_MAP:
writeMap((Map) v);
break;
case VAL_BUNDLE:
writeBundle((Bundle) v);
break;
case VAL_PERSISTABLEBUNDLE:
writePersistableBundle((PersistableBundle) v);
break;
case VAL_PARCELABLE:
writeParcelable((Parcelable) v, 0);
break;
case VAL_SHORT:
writeInt(((Short) v).intValue());
break;
case VAL_LONG:
writeLong((Long) v);
break;
case VAL_FLOAT:
writeFloat((Float) v);
break;
case VAL_DOUBLE:
writeDouble((Double) v);
break;
case VAL_BOOLEAN:
writeInt((Boolean) v ? 1 : 0);
break;
case VAL_CHARSEQUENCE:
writeCharSequence((CharSequence) v);
break;
case VAL_LIST:
writeList((List) v);
break;
case VAL_SPARSEARRAY:
writeSparseArray((SparseArray) v);
break;
case VAL_BOOLEANARRAY:
writeBooleanArray((boolean[]) v);
break;
case VAL_BYTEARRAY:
writeByteArray((byte[]) v);
break;
case VAL_STRINGARRAY:
writeStringArray((String[]) v);
break;
case VAL_CHARSEQUENCEARRAY:
writeCharSequenceArray((CharSequence[]) v);
break;
case VAL_IBINDER:
writeStrongBinder((IBinder) v);
break;
case VAL_PARCELABLEARRAY:
writeParcelableArray((Parcelable[]) v, 0);
break;
case VAL_INTARRAY:
writeIntArray((int[]) v);
break;
case VAL_LONGARRAY:
writeLongArray((long[]) v);
break;
case VAL_BYTE:
writeInt((Byte) v);
break;
case VAL_SIZE:
writeSize((Size) v);
break;
case VAL_SIZEF:
writeSizeF((SizeF) v);
break;
case VAL_DOUBLEARRAY:
writeDoubleArray((double[]) v);
break;
case VAL_CHAR:
writeInt((Character) v);
break;
case VAL_SHORTARRAY:
writeShortArray((short[]) v);
break;
case VAL_CHARARRAY:
writeCharArray((char[]) v);
break;
case VAL_FLOATARRAY:
writeFloatArray((float[]) v);
break;
case VAL_OBJECTARRAY:
writeArray((Object[]) v);
break;
case VAL_SERIALIZABLE:
writeSerializable((Serializable) v);
break;
default:
throw new RuntimeException("Parcel: unable to marshal value " + v);
}
}
/**
* Flatten the name of the class of the Parcelable and its contents
* into the parcel.
*
* @param p The Parcelable object to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
*/
public final void writeParcelable(@Nullable Parcelable p, int parcelableFlags) {
if (p == null) {
writeString(null);
return;
}
writeParcelableCreator(p);
p.writeToParcel(this, parcelableFlags);
}
/**
* Flatten the name of the class of the Parcelable into this Parcel.
*
* @param p The Parcelable object to be written.
* @see #readParcelableCreator
*/
public final void writeParcelableCreator(@NonNull Parcelable p) {
String name = p.getClass().getName();
writeString(name);
}
/**
* A map used by {@link #maybeWriteSquashed} to keep track of what parcelables have
* been seen, and what positions they were written. The value is the absolute position of
* each parcelable.
*/
private ArrayMap<Parcelable, Integer> mWrittenSquashableParcelables;
private void ensureWrittenSquashableParcelables() {
if (mWrittenSquashableParcelables != null) {
return;
}
mWrittenSquashableParcelables = new ArrayMap<>();
}
private boolean mAllowSquashing = false;
/**
* Allow "squashing" writes in {@link #maybeWriteSquashed}. This allows subsequent calls to
* {@link #maybeWriteSquashed(Parcelable)} to "squash" the same instances into one in a Parcel.
*
* Typically, this method is called at the beginning of {@link Parcelable#writeToParcel}. The
* caller must retain the return value from this method and call {@link #restoreAllowSquashing}
* with it.
*
* See {@link #maybeWriteSquashed(Parcelable)} for the details.
*
* @see #restoreAllowSquashing(boolean)
* @see #maybeWriteSquashed(Parcelable)
* @see #readSquashed(SquashReadHelper)
*
* @hide
*/
@TestApi
public boolean allowSquashing() {
boolean previous = mAllowSquashing;
mAllowSquashing = true;
return previous;
}
/**
* @see #allowSquashing()
* @hide
*/
@TestApi
public void restoreAllowSquashing(boolean previous) {
mAllowSquashing = previous;
if (!mAllowSquashing) {
mWrittenSquashableParcelables = null;
}
}
private void resetSqaushingState() {
if (mAllowSquashing) {
Slog.wtf(TAG, "allowSquashing wasn't restored.");
}
mWrittenSquashableParcelables = null;
mReadSquashableParcelables = null;
mAllowSquashing = false;
}
/**
* A map used by {@link #readSquashed} to cache parcelables. It's a map from
* an absolute position in a Parcel to the parcelable stored at the position.
*/
private SparseArray<Parcelable> mReadSquashableParcelables;
private void ensureReadSquashableParcelables() {
if (mReadSquashableParcelables != null) {
return;
}
mReadSquashableParcelables = new SparseArray<>();
}
/**
* Write a parcelable with "squash" -- that is, when the same instance is written to the
* same Parcelable multiple times, instead of writing the entire instance multiple times,
* only write it once, and in subsequent writes we'll only write the offset to the original
* object.
*
* This approach does not work of the resulting Parcel is copied with {@link #appendFrom} with
* a non-zero offset, so we do not enable this behavior by default. Instead, we only enable
* it between {@link #allowSquashing} and {@link #restoreAllowSquashing}, in order to make sure
* we only do so within each "top level" Parcelable.
*
* Usage: Use this method in {@link Parcelable#writeToParcel}.
* If this method returns TRUE, it's a subsequent call, and the offset is already written,
* so the caller doesn't have to do anything. If this method returns FALSE, it's the first
* time for the instance to be written to this parcel. The caller has to proceed with its
* {@link Parcelable#writeToParcel}.
*
* (See {@code ApplicationInfo} for the example.)
*
* @param p the target Parcelable to write.
*
* @see #allowSquashing()
* @see #restoreAllowSquashing(boolean)
* @see #readSquashed(SquashReadHelper)
*
* @hide
*/
public boolean maybeWriteSquashed(@NonNull Parcelable p) {
if (!mAllowSquashing) {
// Don't squash, and don't put it in the map either.
writeInt(0);
return false;
}
ensureWrittenSquashableParcelables();
final Integer firstPos = mWrittenSquashableParcelables.get(p);
if (firstPos != null) {
// Already written.
// Write the relative offset from the current position to the first position.
final int pos = dataPosition();
// We want the offset from the next byte of this integer, so we need to +4.
writeInt(pos - firstPos + 4);
return true;
}
// First time seen, write a marker.
writeInt(0);
// Remember the position.
final int pos = dataPosition();
mWrittenSquashableParcelables.put(p, pos);
// Return false and let the caller actually write the content.
return false;
}
/**
* Helper function that's used by {@link #readSquashed(SquashReadHelper)}
* @hide
*/
public interface SquashReadHelper<T> {
/** Read and instantiate {@code T} from a Parcel. */
@NonNull
T readRawParceled(@NonNull Parcel p);
}
/**
* Read a {@link Parcelable} that's written with {@link #maybeWriteSquashed}.
*
* @param reader a callback function that instantiates an instance from a parcel.
* Typicallly, a lambda to the instructor that takes a {@link Parcel} is passed.
*
* @see #maybeWriteSquashed(Parcelable)
*
* @hide
*/
@SuppressWarnings("unchecked")
@Nullable
public <T extends Parcelable> T readSquashed(SquashReadHelper<T> reader) {
final int offset = readInt();
final int pos = dataPosition();
if (offset == 0) {
// First time read. Unparcel, and remember it.
final T p = reader.readRawParceled(this);
ensureReadSquashableParcelables();
mReadSquashableParcelables.put(pos, p);
return p;
}
// Subsequent read.
final int firstAbsolutePos = pos - offset;
final Parcelable p = mReadSquashableParcelables.get(firstAbsolutePos);
if (p == null) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < mReadSquashableParcelables.size(); i++) {
sb.append(mReadSquashableParcelables.keyAt(i)).append(' ');
}
Slog.wtfStack(TAG, "Map doesn't contain offset "
+ firstAbsolutePos
+ " : contains=" + sb.toString());
}
return (T) p;
}
/**
* Write a generic serializable object in to a Parcel. It is strongly
* recommended that this method be avoided, since the serialization
* overhead is extremely large, and this approach will be much slower than
* using the other approaches to writing data in to a Parcel.
*/
public final void writeSerializable(@Nullable Serializable s) {
if (s == null) {
writeString(null);
return;
}
String name = s.getClass().getName();
writeString(name);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(s);
oos.close();
writeByteArray(baos.toByteArray());
} catch (IOException ioe) {
throw new BadParcelableException("Parcelable encountered "
+ "IOException writing serializable object (name = "
+ name + ")", ioe);
}
}
/** @hide For debugging purposes */
public static void setStackTraceParceling(boolean enabled) {
sParcelExceptionStackTrace = enabled;
}
/**
* Special function for writing an exception result at the header of
* a parcel, to be used when returning an exception from a transaction.
* Note that this currently only supports a few exception types; any other
* exception will be re-thrown by this function as a RuntimeException
* (to be caught by the system's last-resort exception handling when
* dispatching a transaction).
*
* <p>The supported exception types are:
* <ul>
* <li>{@link BadParcelableException}
* <li>{@link IllegalArgumentException}
* <li>{@link IllegalStateException}
* <li>{@link NullPointerException}
* <li>{@link SecurityException}
* <li>{@link UnsupportedOperationException}
* <li>{@link NetworkOnMainThreadException}
* </ul>
*
* @param e The Exception to be written.
*
* @see #writeNoException
* @see #readException
*/
public final void writeException(@NonNull Exception e) {
AppOpsManager.prefixParcelWithAppOpsIfNeeded(this);
int code = getExceptionCode(e);
writeInt(code);
StrictMode.clearGatheredViolations();
if (code == 0) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
writeString(e.getMessage());
final long timeNow = sParcelExceptionStackTrace ? SystemClock.elapsedRealtime() : 0;
if (sParcelExceptionStackTrace && (timeNow - sLastWriteExceptionStackTrace
> WRITE_EXCEPTION_STACK_TRACE_THRESHOLD_MS)) {
sLastWriteExceptionStackTrace = timeNow;
writeStackTrace(e);
} else {
writeInt(0);
}
switch (code) {
case EX_SERVICE_SPECIFIC:
writeInt(((ServiceSpecificException) e).errorCode);
break;
case EX_PARCELABLE:
// Write parceled exception prefixed by length
final int sizePosition = dataPosition();
writeInt(0);
writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
final int payloadPosition = dataPosition();
setDataPosition(sizePosition);
writeInt(payloadPosition - sizePosition);
setDataPosition(payloadPosition);
break;
}
}
/** @hide */
public static int getExceptionCode(@NonNull Throwable e) {
int code = 0;
if (e instanceof Parcelable
&& (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
// We only send Parcelable exceptions that are in the
// BootClassLoader to ensure that the receiver can unpack them
code = EX_PARCELABLE;
} else if (e instanceof SecurityException) {
code = EX_SECURITY;
} else if (e instanceof BadParcelableException) {
code = EX_BAD_PARCELABLE;
} else if (e instanceof IllegalArgumentException) {
code = EX_ILLEGAL_ARGUMENT;
} else if (e instanceof NullPointerException) {
code = EX_NULL_POINTER;
} else if (e instanceof IllegalStateException) {
code = EX_ILLEGAL_STATE;
} else if (e instanceof NetworkOnMainThreadException) {
code = EX_NETWORK_MAIN_THREAD;
} else if (e instanceof UnsupportedOperationException) {
code = EX_UNSUPPORTED_OPERATION;
} else if (e instanceof ServiceSpecificException) {
code = EX_SERVICE_SPECIFIC;
}
return code;
}
/** @hide */
public void writeStackTrace(@NonNull Throwable e) {
final int sizePosition = dataPosition();
writeInt(0); // Header size will be filled in later
StackTraceElement[] stackTrace = e.getStackTrace();
final int truncatedSize = Math.min(stackTrace.length, 5);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < truncatedSize; i++) {
sb.append("\tat ").append(stackTrace[i]).append('\n');
}
writeString(sb.toString());
final int payloadPosition = dataPosition();
setDataPosition(sizePosition);
// Write stack trace header size. Used in native side to skip the header
writeInt(payloadPosition - sizePosition);
setDataPosition(payloadPosition);
}
/**
* Special function for writing information at the front of the Parcel
* indicating that no exception occurred.
*
* @see #writeException
* @see #readException
*/
public final void writeNoException() {
AppOpsManager.prefixParcelWithAppOpsIfNeeded(this);
// Despite the name of this function ("write no exception"),
// it should instead be thought of as "write the RPC response
// header", but because this function name is written out by
// the AIDL compiler, we're not going to rename it.
//
// The response header, in the non-exception case (see also
// writeException above, also called by the AIDL compiler), is
// either a 0 (the default case), or EX_HAS_STRICTMODE_REPLY_HEADER if
// StrictMode has gathered up violations that have occurred
// during a Binder call, in which case we write out the number
// of violations and their details, serialized, before the
// actual RPC respons data. The receiving end of this is
// readException(), below.
if (StrictMode.hasGatheredViolations()) {
writeInt(EX_HAS_STRICTMODE_REPLY_HEADER);
final int sizePosition = dataPosition();
writeInt(0); // total size of fat header, to be filled in later
StrictMode.writeGatheredViolationsToParcel(this);
final int payloadPosition = dataPosition();
setDataPosition(sizePosition);
writeInt(payloadPosition - sizePosition); // header size
setDataPosition(payloadPosition);
} else {
writeInt(0);
}
}
/**
* Special function for reading an exception result from the header of
* a parcel, to be used after receiving the result of a transaction. This
* will throw the exception for you if it had been written to the Parcel,
* otherwise return and let you read the normal result data from the Parcel.
*
* @see #writeException
* @see #writeNoException
*/
public final void readException() {
int code = readExceptionCode();
if (code != 0) {
String msg = readString();
readException(code, msg);
}
}
/**
* Parses the header of a Binder call's response Parcel and
* returns the exception code. Deals with lite or fat headers.
* In the common successful case, this header is generally zero.
* In less common cases, it's a small negative number and will be
* followed by an error string.
*
* This exists purely for android.database.DatabaseUtils and
* insulating it from having to handle fat headers as returned by
* e.g. StrictMode-induced RPC responses.
*
* @hide
*/
@UnsupportedAppUsage
@TestApi
public final int readExceptionCode() {
int code = readInt();
if (code == EX_HAS_NOTED_APPOPS_REPLY_HEADER) {
AppOpsManager.readAndLogNotedAppops(this);
// Read next header or real exception if there is no more header
code = readInt();
}
if (code == EX_HAS_STRICTMODE_REPLY_HEADER) {
int headerSize = readInt();
if (headerSize == 0) {
Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
} else {
// Currently the only thing in the header is StrictMode stacks,
// but discussions around event/RPC tracing suggest we might
// put that here too. If so, switch on sub-header tags here.
// But for now, just parse out the StrictMode stuff.
StrictMode.readAndHandleBinderCallViolations(this);
}
// And fat response headers are currently only used when
// there are no exceptions, so return no error:
return 0;
}
return code;
}
/**
* Throw an exception with the given message. Not intended for use
* outside the Parcel class.
*
* @param code Used to determine which exception class to throw.
* @param msg The exception message.
*/
public final void readException(int code, String msg) {
String remoteStackTrace = null;
final int remoteStackPayloadSize = readInt();
if (remoteStackPayloadSize > 0) {
remoteStackTrace = readString();
}
Exception e = createException(code, msg);
// Attach remote stack trace if availalble
if (remoteStackTrace != null) {
RemoteException cause = new RemoteException(
"Remote stack trace:\n" + remoteStackTrace, null, false, false);
ExceptionUtils.appendCause(e, cause);
}
SneakyThrow.sneakyThrow(e);
}
/**
* Creates an exception with the given message.
*
* @param code Used to determine which exception class to throw.
* @param msg The exception message.
*/
private Exception createException(int code, String msg) {
Exception exception = createExceptionOrNull(code, msg);
return exception != null
? exception
: new RuntimeException("Unknown exception code: " + code + " msg " + msg);
}
/** @hide */
public Exception createExceptionOrNull(int code, String msg) {
switch (code) {
case EX_PARCELABLE:
if (readInt() > 0) {
return (Exception) readParcelable(Parcelable.class.getClassLoader());
} else {
return new RuntimeException(msg + " [missing Parcelable]");
}
case EX_SECURITY:
return new SecurityException(msg);
case EX_BAD_PARCELABLE:
return new BadParcelableException(msg);
case EX_ILLEGAL_ARGUMENT:
return new IllegalArgumentException(msg);
case EX_NULL_POINTER:
return new NullPointerException(msg);
case EX_ILLEGAL_STATE:
return new IllegalStateException(msg);
case EX_NETWORK_MAIN_THREAD:
return new NetworkOnMainThreadException();
case EX_UNSUPPORTED_OPERATION:
return new UnsupportedOperationException(msg);
case EX_SERVICE_SPECIFIC:
return new ServiceSpecificException(readInt(), msg);
default:
return null;
}
}
/**
* Read an integer value from the parcel at the current dataPosition().
*/
public final int readInt() {
return nativeReadInt(mNativePtr);
}
/**
* Read a long integer value from the parcel at the current dataPosition().
*/
public final long readLong() {
return nativeReadLong(mNativePtr);
}
/**
* Read a floating point value from the parcel at the current
* dataPosition().
*/
public final float readFloat() {
return nativeReadFloat(mNativePtr);
}
/**
* Read a double precision floating point value from the parcel at the
* current dataPosition().
*/
public final double readDouble() {
return nativeReadDouble(mNativePtr);
}
/**
* Read a string value from the parcel at the current dataPosition().
*/
@Nullable
public final String readString() {
return readString16();
}
/** {@hide} */
public final @Nullable String readString8() {
return mReadWriteHelper.readString8(this);
}
/** {@hide} */
public final @Nullable String readString16() {
return mReadWriteHelper.readString16(this);
}
/**
* Read a string without going though a {@link ReadWriteHelper}. Subclasses of
* {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
* infinity recursive calls.
*
* @hide
*/
public @Nullable String readStringNoHelper() {
return readString16NoHelper();
}
/** {@hide} */
public @Nullable String readString8NoHelper() {
return nativeReadString8(mNativePtr);
}
/** {@hide} */
public @Nullable String readString16NoHelper() {
return nativeReadString16(mNativePtr);
}
/**
* Read a boolean value from the parcel at the current dataPosition().
*/
public final boolean readBoolean() {
return readInt() != 0;
}
/**
* Read a CharSequence value from the parcel at the current dataPosition().
* @hide
*/
@UnsupportedAppUsage
@Nullable
public final CharSequence readCharSequence() {
return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
}
/**
* Read an object from the parcel at the current dataPosition().
*/
public final IBinder readStrongBinder() {
final IBinder result = nativeReadStrongBinder(mNativePtr);
// If it's a reply from a method with @PropagateAllowBlocking, then inherit allow-blocking
// from the object that returned it.
if (result != null && hasFlags(
FLAG_IS_REPLY_FROM_BLOCKING_ALLOWED_OBJECT | FLAG_PROPAGATE_ALLOW_BLOCKING)) {
Binder.allowBlocking(result);
}
return result;
}
/**
* Read a FileDescriptor from the parcel at the current dataPosition().
*/
public final ParcelFileDescriptor readFileDescriptor() {
FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
return fd != null ? new ParcelFileDescriptor(fd) : null;
}
/** {@hide} */
@UnsupportedAppUsage
public final FileDescriptor readRawFileDescriptor() {
return nativeReadFileDescriptor(mNativePtr);
}
/**
* {@hide}
* Read and return a new array of FileDescriptors from the parcel.
* @return the FileDescriptor array, or null if the array is null.
**/
@Nullable
public final FileDescriptor[] createRawFileDescriptorArray() {
int N = readInt();
if (N < 0) {
return null;
}
FileDescriptor[] f = new FileDescriptor[N];
for (int i = 0; i < N; i++) {
f[i] = readRawFileDescriptor();
}
return f;
}
/**
* {@hide}
* Read an array of FileDescriptors from a parcel.
* The passed array must be exactly the length of the array in the parcel.
* @return the FileDescriptor array, or null if the array is null.
**/
public final void readRawFileDescriptorArray(FileDescriptor[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readRawFileDescriptor();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
/**
* Read a byte value from the parcel at the current dataPosition().
*/
public final byte readByte() {
return (byte)(readInt() & 0xff);
}
/**
* Please use {@link #readBundle(ClassLoader)} instead (whose data must have
* been written with {@link #writeBundle}. Read into an existing Map object
* from the parcel at the current dataPosition().
*
* @deprecated Consider using {@link #readBundle(ClassLoader)} as stated above, in case this
* method is still preferred use the type-safer version {@link #readMap(Map, ClassLoader,
* Class, Class)} starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
*/
@Deprecated
public final void readMap(@NonNull Map outVal, @Nullable ClassLoader loader) {
readMapInternal(outVal, loader, /* clazzKey */ null, /* clazzValue */ null);
}
/**
* Same as {@link #readMap(Map, ClassLoader)} but accepts {@code clazzKey} and
* {@code clazzValue} parameter as the types required for each key and value pair.
*
* @throws BadParcelableException If the item to be deserialized is not an instance of that
* class or any of its children class
*/
public <K, V> void readMap(@NonNull Map<? super K, ? super V> outVal,
@Nullable ClassLoader loader, @NonNull Class<K> clazzKey,
@NonNull Class<V> clazzValue) {
Objects.requireNonNull(clazzKey);
Objects.requireNonNull(clazzValue);
readMapInternal(outVal, loader, clazzKey, clazzValue);
}
/**
* Read into an existing List object from the parcel at the current
* dataPosition(), using the given class loader to load any enclosed
* Parcelables. If it is null, the default class loader is used.
*
* @deprecated Use the type-safer version {@link #readList(List, ClassLoader, Class)} starting
* from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
* use {@link #readTypedList(List, Parcelable.Creator)} if possible (eg. if the items'
* class is final) since this is also more performant. Note that changing to the latter
* also requires changing the writes.
*/
@Deprecated
public final void readList(@NonNull List outVal, @Nullable ClassLoader loader) {
int N = readInt();
readListInternal(outVal, N, loader, /* clazz */ null);
}
/**
* Same as {@link #readList(List, ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
* the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readList(List, ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
public <T> void readList(@NonNull List<? super T> outVal,
@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
Objects.requireNonNull(clazz);
int n = readInt();
readListInternal(outVal, n, loader, clazz);
}
/**
* Please use {@link #readBundle(ClassLoader)} instead (whose data must have
* been written with {@link #writeBundle}. Read and return a new HashMap
* object from the parcel at the current dataPosition(), using the given
* class loader to load any enclosed Parcelables. Returns null if
* the previously written map object was null.
*
* @deprecated Consider using {@link #readBundle(ClassLoader)} as stated above, in case this
* method is still preferred use the type-safer version {@link #readHashMap(ClassLoader,
* Class, Class)} starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
*/
@Deprecated
@Nullable
public HashMap readHashMap(@Nullable ClassLoader loader) {
return readHashMapInternal(loader, /* clazzKey */ null, /* clazzValue */ null);
}
/**
* Same as {@link #readHashMap(ClassLoader)} but accepts {@code clazzKey} and
* {@code clazzValue} parameter as the types required for each key and value pair.
*
* @throws BadParcelableException if the item to be deserialized is not an instance of that
* class or any of its children class
*/
@SuppressLint({"ConcreteCollection", "NullableCollection"})
@Nullable
public <K, V> HashMap<K, V> readHashMap(@Nullable ClassLoader loader,
@NonNull Class<? extends K> clazzKey, @NonNull Class<? extends V> clazzValue) {
Objects.requireNonNull(clazzKey);
Objects.requireNonNull(clazzValue);
return readHashMapInternal(loader, clazzKey, clazzValue);
}
/**
* Read and return a new Bundle object from the parcel at the current
* dataPosition(). Returns null if the previously written Bundle object was
* null.
*/
@Nullable
public final Bundle readBundle() {
return readBundle(null);
}
/**
* Read and return a new Bundle object from the parcel at the current
* dataPosition(), using the given class loader to initialize the class
* loader of the Bundle for later retrieval of Parcelable objects.
* Returns null if the previously written Bundle object was null.
*/
@Nullable
public final Bundle readBundle(@Nullable ClassLoader loader) {
int length = readInt();
if (length < 0) {
if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
return null;
}
final Bundle bundle = new Bundle(this, length);
if (loader != null) {
bundle.setClassLoader(loader);
}
return bundle;
}
/**
* Read and return a new Bundle object from the parcel at the current
* dataPosition(). Returns null if the previously written Bundle object was
* null.
*/
@Nullable
public final PersistableBundle readPersistableBundle() {
return readPersistableBundle(null);
}
/**
* Read and return a new Bundle object from the parcel at the current
* dataPosition(), using the given class loader to initialize the class
* loader of the Bundle for later retrieval of Parcelable objects.
* Returns null if the previously written Bundle object was null.
*/
@Nullable
public final PersistableBundle readPersistableBundle(@Nullable ClassLoader loader) {
int length = readInt();
if (length < 0) {
if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
return null;
}
final PersistableBundle bundle = new PersistableBundle(this, length);
if (loader != null) {
bundle.setClassLoader(loader);
}
return bundle;
}
/**
* Read a Size from the parcel at the current dataPosition().
*/
@NonNull
public final Size readSize() {
final int width = readInt();
final int height = readInt();
return new Size(width, height);
}
/**
* Read a SizeF from the parcel at the current dataPosition().
*/
@NonNull
public final SizeF readSizeF() {
final float width = readFloat();
final float height = readFloat();
return new SizeF(width, height);
}
/**
* Read and return a byte[] object from the parcel.
*/
@Nullable
public final byte[] createByteArray() {
return nativeCreateByteArray(mNativePtr);
}
/**
* Read a byte[] object from the parcel and copy it into the
* given byte array.
*/
public final void readByteArray(@NonNull byte[] val) {
boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
if (!valid) {
throw new RuntimeException("bad array lengths");
}
}
/**
* Read a blob of data from the parcel and return it as a byte array.
* @see #writeBlob(byte[], int, int)
*/
@Nullable
public final byte[] readBlob() {
return nativeReadBlob(mNativePtr);
}
/**
* Read and return a String[] object from the parcel.
* {@hide}
*/
@UnsupportedAppUsage
@Nullable
public final String[] readStringArray() {
return createString16Array();
}
/**
* Read and return a CharSequence[] object from the parcel.
* {@hide}
*/
@Nullable
public final CharSequence[] readCharSequenceArray() {
CharSequence[] array = null;
int length = readInt();
if (length >= 0)
{
array = new CharSequence[length];
for (int i = 0 ; i < length ; i++)
{
array[i] = readCharSequence();
}
}
return array;
}
/**
* Read and return an ArrayList<CharSequence> object from the parcel.
* {@hide}
*/
@Nullable
public final ArrayList<CharSequence> readCharSequenceList() {
ArrayList<CharSequence> array = null;
int length = readInt();
if (length >= 0) {
array = new ArrayList<CharSequence>(length);
for (int i = 0 ; i < length ; i++) {
array.add(readCharSequence());
}
}
return array;
}
/**
* Read and return a new ArrayList object from the parcel at the current
* dataPosition(). Returns null if the previously written list object was
* null. The given class loader will be used to load any enclosed
* Parcelables.
*
* @deprecated Use the type-safer version {@link #readArrayList(ClassLoader, Class)} starting
* from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
* use {@link #createTypedArrayList(Parcelable.Creator)} if possible (eg. if the items'
* class is final) since this is also more performant. Note that changing to the latter
* also requires changing the writes.
*/
@Deprecated
@Nullable
public ArrayList readArrayList(@Nullable ClassLoader loader) {
return readArrayListInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readArrayList(ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
* the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readArrayList(ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@SuppressLint({"ConcreteCollection", "NullableCollection"})
@Nullable
public <T> ArrayList<T> readArrayList(@Nullable ClassLoader loader,
@NonNull Class<? extends T> clazz) {
Objects.requireNonNull(clazz);
return readArrayListInternal(loader, clazz);
}
/**
* Read and return a new Object array from the parcel at the current
* dataPosition(). Returns null if the previously written array was
* null. The given class loader will be used to load any enclosed
* Parcelables.
*
* @deprecated Use the type-safer version {@link #readArray(ClassLoader, Class)} starting from
* Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to use
* {@link #createTypedArray(Parcelable.Creator)} if possible (eg. if the items' class is
* final) since this is also more performant. Note that changing to the latter also
* requires changing the writes.
*/
@Deprecated
@Nullable
public Object[] readArray(@Nullable ClassLoader loader) {
return readArrayInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readArray(ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
* the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readArray(ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@SuppressLint({"ArrayReturn", "NullableCollection"})
@Nullable
public <T> T[] readArray(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
Objects.requireNonNull(clazz);
return readArrayInternal(loader, clazz);
}
/**
* Read and return a new SparseArray object from the parcel at the current
* dataPosition(). Returns null if the previously written list object was
* null. The given class loader will be used to load any enclosed
* Parcelables.
*
* @deprecated Use the type-safer version {@link #readSparseArray(ClassLoader, Class)} starting
* from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
* use {@link #createTypedSparseArray(Parcelable.Creator)} if possible (eg. if the items'
* class is final) since this is also more performant. Note that changing to the latter
* also requires changing the writes.
*/
@Deprecated
@Nullable
public <T> SparseArray<T> readSparseArray(@Nullable ClassLoader loader) {
return readSparseArrayInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readSparseArray(ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
* the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readSparseArray(ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@Nullable
public <T> SparseArray<T> readSparseArray(@Nullable ClassLoader loader,
@NonNull Class<? extends T> clazz) {
Objects.requireNonNull(clazz);
return readSparseArrayInternal(loader, clazz);
}
/**
* Read and return a new SparseBooleanArray object from the parcel at the current
* dataPosition(). Returns null if the previously written list object was
* null.
*/
@Nullable
public final SparseBooleanArray readSparseBooleanArray() {
int N = readInt();
if (N < 0) {
return null;
}
SparseBooleanArray sa = new SparseBooleanArray(N);
readSparseBooleanArrayInternal(sa, N);
return sa;
}
/**
* Read and return a new SparseIntArray object from the parcel at the current
* dataPosition(). Returns null if the previously written array object was null.
* @hide
*/
@Nullable
public final SparseIntArray readSparseIntArray() {
int N = readInt();
if (N < 0) {
return null;
}
SparseIntArray sa = new SparseIntArray(N);
readSparseIntArrayInternal(sa, N);
return sa;
}
/**
* Read and return a new ArrayList containing a particular object type from
* the parcel that was written with {@link #writeTypedList} at the
* current dataPosition(). Returns null if the
* previously written list object was null. The list <em>must</em> have
* previously been written via {@link #writeTypedList} with the same object
* type.
*
* @return A newly created ArrayList containing objects with the same data
* as those that were previously written.
*
* @see #writeTypedList
*/
@Nullable
public final <T> ArrayList<T> createTypedArrayList(@NonNull Parcelable.Creator<T> c) {
int N = readInt();
if (N < 0) {
return null;
}
ArrayList<T> l = new ArrayList<T>(N);
while (N > 0) {
l.add(readTypedObject(c));
N--;
}
return l;
}
/**
* Read into the given List items containing a particular object type
* that were written with {@link #writeTypedList} at the
* current dataPosition(). The list <em>must</em> have
* previously been written via {@link #writeTypedList} with the same object
* type.
*
* @return A newly created ArrayList containing objects with the same data
* as those that were previously written.
*
* @see #writeTypedList
*/
public final <T> void readTypedList(@NonNull List<T> list, @NonNull Parcelable.Creator<T> c) {
int M = list.size();
int N = readInt();
int i = 0;
for (; i < M && i < N; i++) {
list.set(i, readTypedObject(c));
}
for (; i<N; i++) {
list.add(readTypedObject(c));
}
for (; i<M; i++) {
list.remove(N);
}
}
/**
* Read into a new {@link SparseArray} items containing a particular object type
* that were written with {@link #writeTypedSparseArray(SparseArray, int)} at the
* current dataPosition(). The list <em>must</em> have previously been written
* via {@link #writeTypedSparseArray(SparseArray, int)} with the same object type.
*
* @param creator The creator to use when for instantiation.
*
* @return A newly created {@link SparseArray} containing objects with the same data
* as those that were previously written.
*
* @see #writeTypedSparseArray(SparseArray, int)
*/
public final @Nullable <T extends Parcelable> SparseArray<T> createTypedSparseArray(
@NonNull Parcelable.Creator<T> creator) {
final int count = readInt();
if (count < 0) {
return null;
}
final SparseArray<T> array = new SparseArray<>(count);
for (int i = 0; i < count; i++) {
final int index = readInt();
final T value = readTypedObject(creator);
array.append(index, value);
}
return array;
}
/**
* Read into a new {@link ArrayMap} with string keys items containing a particular
* object type that were written with {@link #writeTypedArrayMap(ArrayMap, int)} at the
* current dataPosition(). The list <em>must</em> have previously been written
* via {@link #writeTypedArrayMap(ArrayMap, int)} with the same object type.
*
* @param creator The creator to use when for instantiation.
*
* @return A newly created {@link ArrayMap} containing objects with the same data
* as those that were previously written.
*
* @see #writeTypedArrayMap(ArrayMap, int)
*/
public final @Nullable <T extends Parcelable> ArrayMap<String, T> createTypedArrayMap(
@NonNull Parcelable.Creator<T> creator) {
final int count = readInt();
if (count < 0) {
return null;
}
final ArrayMap<String, T> map = new ArrayMap<>(count);
for (int i = 0; i < count; i++) {
final String key = readString();
final T value = readTypedObject(creator);
map.append(key, value);
}
return map;
}
/**
* Read and return a new ArrayList containing String objects from
* the parcel that was written with {@link #writeStringList} at the
* current dataPosition(). Returns null if the
* previously written list object was null.
*
* @return A newly created ArrayList containing strings with the same data
* as those that were previously written.
*
* @see #writeStringList
*/
@Nullable
public final ArrayList<String> createStringArrayList() {
int N = readInt();
if (N < 0) {
return null;
}
ArrayList<String> l = new ArrayList<String>(N);
while (N > 0) {
l.add(readString());
N--;
}
return l;
}
/**
* Read and return a new ArrayList containing IBinder objects from
* the parcel that was written with {@link #writeBinderList} at the
* current dataPosition(). Returns null if the
* previously written list object was null.
*
* @return A newly created ArrayList containing strings with the same data
* as those that were previously written.
*
* @see #writeBinderList
*/
@Nullable
public final ArrayList<IBinder> createBinderArrayList() {
int N = readInt();
if (N < 0) {
return null;
}
ArrayList<IBinder> l = new ArrayList<IBinder>(N);
while (N > 0) {
l.add(readStrongBinder());
N--;
}
return l;
}
/**
* Read and return a new ArrayList containing T (IInterface) objects from
* the parcel that was written with {@link #writeInterfaceList} at the
* current dataPosition(). Returns null if the
* previously written list object was null.
*
* @return A newly created ArrayList containing T (IInterface)
*
* @see #writeInterfaceList
*/
@SuppressLint({"ConcreteCollection", "NullableCollection"})
@Nullable
public final <T extends IInterface> ArrayList<T> createInterfaceArrayList(
@NonNull Function<IBinder, T> asInterface) {
int N = readInt();
if (N < 0) {
return null;
}
ArrayList<T> l = new ArrayList<T>(N);
while (N > 0) {
l.add(asInterface.apply(readStrongBinder()));
N--;
}
return l;
}
/**
* Read into the given List items String objects that were written with
* {@link #writeStringList} at the current dataPosition().
*
* @see #writeStringList
*/
public final void readStringList(@NonNull List<String> list) {
int M = list.size();
int N = readInt();
int i = 0;
for (; i < M && i < N; i++) {
list.set(i, readString());
}
for (; i<N; i++) {
list.add(readString());
}
for (; i<M; i++) {
list.remove(N);
}
}
/**
* Read into the given List items IBinder objects that were written with
* {@link #writeBinderList} at the current dataPosition().
*
* @see #writeBinderList
*/
public final void readBinderList(@NonNull List<IBinder> list) {
int M = list.size();
int N = readInt();
int i = 0;
for (; i < M && i < N; i++) {
list.set(i, readStrongBinder());
}
for (; i<N; i++) {
list.add(readStrongBinder());
}
for (; i<M; i++) {
list.remove(N);
}
}
/**
* Read into the given List items IInterface objects that were written with
* {@link #writeInterfaceList} at the current dataPosition().
*
* @see #writeInterfaceList
*/
public final <T extends IInterface> void readInterfaceList(@NonNull List<T> list,
@NonNull Function<IBinder, T> asInterface) {
int M = list.size();
int N = readInt();
int i = 0;
for (; i < M && i < N; i++) {
list.set(i, asInterface.apply(readStrongBinder()));
}
for (; i<N; i++) {
list.add(asInterface.apply(readStrongBinder()));
}
for (; i<M; i++) {
list.remove(N);
}
}
/**
* Read the list of {@code Parcelable} objects at the current data position into the
* given {@code list}. The contents of the {@code list} are replaced. If the serialized
* list was {@code null}, {@code list} is cleared.
*
* @see #writeParcelableList(List, int)
*
* @deprecated Use the type-safer version {@link #readParcelableList(List, ClassLoader, Class)}
* starting from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the
* format to use {@link #readTypedList(List, Parcelable.Creator)} if possible (eg. if the
* items' class is final) since this is also more performant. Note that changing to the
* latter also requires changing the writes.
*/
@Deprecated
@NonNull
public final <T extends Parcelable> List<T> readParcelableList(@NonNull List<T> list,
@Nullable ClassLoader cl) {
return readParcelableListInternal(list, cl, /*clazz*/ null);
}
/**
* Same as {@link #readParcelableList(List, ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> if the list contains items implementing the {@link Parcelable} interface,
* the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readParcelableList(List, ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@NonNull
public <T> List<T> readParcelableList(@NonNull List<T> list,
@Nullable ClassLoader cl, @NonNull Class<? extends T> clazz) {
Objects.requireNonNull(list);
Objects.requireNonNull(clazz);
return readParcelableListInternal(list, cl, clazz);
}
/**
* @param clazz The type of the object expected or {@code null} for performing no checks.
*/
@NonNull
private <T> List<T> readParcelableListInternal(@NonNull List<T> list,
@Nullable ClassLoader cl, @Nullable Class<? extends T> clazz) {
final int n = readInt();
if (n == -1) {
list.clear();
return list;
}
final int m = list.size();
int i = 0;
for (; i < m && i < n; i++) {
list.set(i, (T) readParcelableInternal(cl, clazz));
}
for (; i < n; i++) {
list.add((T) readParcelableInternal(cl, clazz));
}
for (; i < m; i++) {
list.remove(n);
}
return list;
}
/**
* Read and return a new array containing a particular object type from
* the parcel at the current dataPosition(). Returns null if the
* previously written array was null. The array <em>must</em> have
* previously been written via {@link #writeTypedArray} with the same
* object type.
*
* @return A newly created array containing objects with the same data
* as those that were previously written.
*
* @see #writeTypedArray
*/
@Nullable
public final <T> T[] createTypedArray(@NonNull Parcelable.Creator<T> c) {
int N = readInt();
if (N < 0) {
return null;
}
T[] l = c.newArray(N);
for (int i=0; i<N; i++) {
l[i] = readTypedObject(c);
}
return l;
}
public final <T> void readTypedArray(@NonNull T[] val, @NonNull Parcelable.Creator<T> c) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readTypedObject(c);
}
} else {
throw new RuntimeException("bad array lengths");
}
}
/**
* @deprecated
* @hide
*/
@Deprecated
public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
return createTypedArray(c);
}
/**
* Read and return a typed Parcelable object from a parcel.
* Returns null if the previous written object was null.
* The object <em>must</em> have previous been written via
* {@link #writeTypedObject} with the same object type.
*
* @return A newly created object of the type that was previously
* written.
*
* @see #writeTypedObject
*/
@Nullable
public final <T> T readTypedObject(@NonNull Parcelable.Creator<T> c) {
if (readInt() != 0) {
return c.createFromParcel(this);
} else {
return null;
}
}
/**
* Read a new multi-dimensional array from a parcel. If you want to read Parcelable or
* IInterface values, use {@link #readFixedArray(Object, Parcelable.Creator)} or
* {@link #readFixedArray(Object, Function)}.
* @param val the destination array to hold the read values.
*
* @see #writeTypedArray
* @see #readBooleanArray
* @see #readByteArray
* @see #readCharArray
* @see #readIntArray
* @see #readLongArray
* @see #readFloatArray
* @see #readDoubleArray
* @see #readBinderArray
* @see #readInterfaceArray
* @see #readTypedArray
*/
public <T> void readFixedArray(@NonNull T val) {
Class<?> componentType = val.getClass().getComponentType();
if (componentType == boolean.class) {
readBooleanArray((boolean[]) val);
} else if (componentType == byte.class) {
readByteArray((byte[]) val);
} else if (componentType == char.class) {
readCharArray((char[]) val);
} else if (componentType == int.class) {
readIntArray((int[]) val);
} else if (componentType == long.class) {
readLongArray((long[]) val);
} else if (componentType == float.class) {
readFloatArray((float[]) val);
} else if (componentType == double.class) {
readDoubleArray((double[]) val);
} else if (componentType == IBinder.class) {
readBinderArray((IBinder[]) val);
} else if (componentType.isArray()) {
int length = readInt();
if (length != Array.getLength(val)) {
throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
+ ", but got " + length);
}
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i));
}
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
}
/**
* Read a new multi-dimensional array of typed interfaces from a parcel.
* If you want to read Parcelable values, use
* {@link #readFixedArray(Object, Parcelable.Creator)}. For values of other types, use
* {@link #readFixedArray(Object)}.
* @param val the destination array to hold the read values.
*/
public <T, S extends IInterface> void readFixedArray(@NonNull T val,
@NonNull Function<IBinder, S> asInterface) {
Class<?> componentType = val.getClass().getComponentType();
if (IInterface.class.isAssignableFrom(componentType)) {
readInterfaceArray((S[]) val, asInterface);
} else if (componentType.isArray()) {
int length = readInt();
if (length != Array.getLength(val)) {
throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
+ ", but got " + length);
}
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i), asInterface);
}
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
}
/**
* Read a new multi-dimensional array of typed parcelables from a parcel.
* If you want to read IInterface values, use
* {@link #readFixedArray(Object, Function)}. For values of other types, use
* {@link #readFixedArray(Object)}.
* @param val the destination array to hold the read values.
*/
public <T, S extends Parcelable> void readFixedArray(@NonNull T val,
@NonNull Parcelable.Creator<S> c) {
Class<?> componentType = val.getClass().getComponentType();
if (Parcelable.class.isAssignableFrom(componentType)) {
readTypedArray((S[]) val, c);
} else if (componentType.isArray()) {
int length = readInt();
if (length != Array.getLength(val)) {
throw new BadParcelableException("Bad length: expected " + Array.getLength(val)
+ ", but got " + length);
}
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i), c);
}
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
}
private void ensureClassHasExpectedDimensions(@NonNull Class<?> cls, int numDimension) {
if (numDimension <= 0) {
throw new BadParcelableException("Fixed-size array should have dimensions.");
}
for (int i = 0; i < numDimension; i++) {
if (!cls.isArray()) {
throw new BadParcelableException("Array has fewer dimensions than expected: "
+ numDimension);
}
cls = cls.getComponentType();
}
if (cls.isArray()) {
throw new BadParcelableException("Array has more dimensions than expected: "
+ numDimension);
}
}
/**
* Read and return a new multi-dimensional array from a parcel. Returns null if the
* previously written array object is null. If you want to read Parcelable or
* IInterface values, use {@link #createFixedArray(Class, Parcelable.Creator, int[])} or
* {@link #createFixedArray(Class, Function, int[])}.
* @param cls the Class object for the target array type. (e.g. int[][].class)
* @param dimensions an array of int representing length of each dimension.
*
* @see #writeTypedArray
* @see #createBooleanArray
* @see #createByteArray
* @see #createCharArray
* @see #createIntArray
* @see #createLongArray
* @see #createFloatArray
* @see #createDoubleArray
* @see #createBinderArray
* @see #createInterfaceArray
* @see #createTypedArray
*/
@Nullable
public <T> T createFixedArray(@NonNull Class<T> cls, @NonNull int... dimensions) {
// Check if type matches with dimensions
// If type is one-dimensional array, delegate to other creators
// Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
ensureClassHasExpectedDimensions(cls, dimensions.length);
T val = null;
final Class<?> componentType = cls.getComponentType();
if (componentType == boolean.class) {
val = (T) createBooleanArray();
} else if (componentType == byte.class) {
val = (T) createByteArray();
} else if (componentType == char.class) {
val = (T) createCharArray();
} else if (componentType == int.class) {
val = (T) createIntArray();
} else if (componentType == long.class) {
val = (T) createLongArray();
} else if (componentType == float.class) {
val = (T) createFloatArray();
} else if (componentType == double.class) {
val = (T) createDoubleArray();
} else if (componentType == IBinder.class) {
val = (T) createBinderArray();
} else if (componentType.isArray()) {
int length = readInt();
if (length < 0) {
return null;
}
if (length != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0]
+ ", but got " + length);
}
// Create a multi-dimensional array with an innermost component type and dimensions
Class<?> innermost = componentType.getComponentType();
while (innermost.isArray()) {
innermost = innermost.getComponentType();
}
val = (T) Array.newInstance(innermost, dimensions);
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i));
}
return val;
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
// Check if val is null (which is OK) or has the expected size.
// This check doesn't have to be multi-dimensional because multi-dimensional arrays
// are created with expected dimensions.
if (val != null && Array.getLength(val) != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
+ Array.getLength(val));
}
return val;
}
/**
* Read and return a new multi-dimensional array of typed interfaces from a parcel.
* Returns null if the previously written array object is null. If you want to read
* Parcelable values, use {@link #createFixedArray(Class, Parcelable.Creator, int[])}.
* For values of other types use {@link #createFixedArray(Class, int[])}.
* @param cls the Class object for the target array type. (e.g. IFoo[][].class)
* @param dimensions an array of int representing length of each dimension.
*/
@Nullable
public <T, S extends IInterface> T createFixedArray(@NonNull Class<T> cls,
@NonNull Function<IBinder, S> asInterface, @NonNull int... dimensions) {
// Check if type matches with dimensions
// If type is one-dimensional array, delegate to other creators
// Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
ensureClassHasExpectedDimensions(cls, dimensions.length);
T val = null;
final Class<?> componentType = cls.getComponentType();
if (IInterface.class.isAssignableFrom(componentType)) {
val = (T) createInterfaceArray(n -> (S[]) Array.newInstance(componentType, n),
asInterface);
} else if (componentType.isArray()) {
int length = readInt();
if (length < 0) {
return null;
}
if (length != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0]
+ ", but got " + length);
}
// Create a multi-dimensional array with an innermost component type and dimensions
Class<?> innermost = componentType.getComponentType();
while (innermost.isArray()) {
innermost = innermost.getComponentType();
}
val = (T) Array.newInstance(innermost, dimensions);
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i), asInterface);
}
return val;
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
// Check if val is null (which is OK) or has the expected size.
// This check doesn't have to be multi-dimensional because multi-dimensional arrays
// are created with expected dimensions.
if (val != null && Array.getLength(val) != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
+ Array.getLength(val));
}
return val;
}
/**
* Read and return a new multi-dimensional array of typed parcelables from a parcel.
* Returns null if the previously written array object is null. If you want to read
* IInterface values, use {@link #createFixedArray(Class, Function, int[])}.
* For values of other types use {@link #createFixedArray(Class, int[])}.
* @param cls the Class object for the target array type. (e.g. Foo[][].class)
* @param dimensions an array of int representing length of each dimension.
*/
@Nullable
public <T, S extends Parcelable> T createFixedArray(@NonNull Class<T> cls,
@NonNull Parcelable.Creator<S> c, @NonNull int... dimensions) {
// Check if type matches with dimensions
// If type is one-dimensional array, delegate to other creators
// Otherwise, create an multi-dimensional array at once and then fill it with readFixedArray
ensureClassHasExpectedDimensions(cls, dimensions.length);
T val = null;
final Class<?> componentType = cls.getComponentType();
if (Parcelable.class.isAssignableFrom(componentType)) {
val = (T) createTypedArray(c);
} else if (componentType.isArray()) {
int length = readInt();
if (length < 0) {
return null;
}
if (length != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0]
+ ", but got " + length);
}
// Create a multi-dimensional array with an innermost component type and dimensions
Class<?> innermost = componentType.getComponentType();
while (innermost.isArray()) {
innermost = innermost.getComponentType();
}
val = (T) Array.newInstance(innermost, dimensions);
for (int i = 0; i < length; i++) {
readFixedArray(Array.get(val, i), c);
}
return val;
} else {
throw new BadParcelableException("Unknown type for fixed-size array: " + componentType);
}
// Check if val is null (which is OK) or has the expected size.
// This check doesn't have to be multi-dimensional because multi-dimensional arrays
// are created with expected dimensions.
if (val != null && Array.getLength(val) != dimensions[0]) {
throw new BadParcelableException("Bad length: expected " + dimensions[0] + ", but got "
+ Array.getLength(val));
}
return val;
}
/**
* Write a heterogeneous array of Parcelable objects into the Parcel.
* Each object in the array is written along with its class name, so
* that the correct class can later be instantiated. As a result, this
* has significantly more overhead than {@link #writeTypedArray}, but will
* correctly handle an array containing more than one type of object.
*
* @param value The array of objects to be written.
* @param parcelableFlags Contextual flags as per
* {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
*
* @see #writeTypedArray
*/
public final <T extends Parcelable> void writeParcelableArray(@Nullable T[] value,
int parcelableFlags) {
if (value != null) {
int N = value.length;
writeInt(N);
for (int i=0; i<N; i++) {
writeParcelable(value[i], parcelableFlags);
}
} else {
writeInt(-1);
}
}
/**
* Read a typed object from a parcel. The given class loader will be
* used to load any enclosed Parcelables. If it is null, the default class
* loader will be used.
*/
@Nullable
public final Object readValue(@Nullable ClassLoader loader) {
return readValue(loader, /* clazz */ null);
}
/**
* @see #readValue(int, ClassLoader, Class, Class[])
*/
@Nullable
private <T> T readValue(@Nullable ClassLoader loader, @Nullable Class<T> clazz,
@Nullable Class<?>... itemTypes) {
int type = readInt();
final T object;
if (isLengthPrefixed(type)) {
int length = readInt();
int start = dataPosition();
object = readValue(type, loader, clazz, itemTypes);
int actual = dataPosition() - start;
if (actual != length) {
Slog.wtfStack(TAG,
"Unparcelling of " + object + " of type " + Parcel.valueTypeToString(type)
+ " consumed " + actual + " bytes, but " + length + " expected.");
}
} else {
object = readValue(type, loader, clazz, itemTypes);
}
return object;
}
/**
* This will return a {@link BiFunction} for length-prefixed types that deserializes the object
* when {@link BiFunction#apply} is called (the arguments correspond to the ones of {@link
* #readValue(int, ClassLoader, Class, Class[])} after the class loader), for other types it
* will return the object itself.
*
* <p>After calling {@link BiFunction#apply} the parcel cursor will not change. Note that you
* shouldn't recycle the parcel, not at least until all objects have been retrieved. No
* synchronization attempts are made.
*
* </p>The function returned implements {@link #equals(Object)} and {@link #hashCode()}. Two
* function objects are equal if either of the following is true:
* <ul>
* <li>{@link BiFunction#apply} has been called on both and both objects returned are equal.
* <li>{@link BiFunction#apply} hasn't been called on either one and everything below is true:
* <ul>
* <li>The {@code loader} parameters used to retrieve each are equal.
* <li>They both have the same type.
* <li>They have the same payload length.
* <li>Their binary content is the same.
* </ul>
* </ul>
*
* @hide
*/
@Nullable
public Object readLazyValue(@Nullable ClassLoader loader) {
int start = dataPosition();
int type = readInt();
if (isLengthPrefixed(type)) {
int objectLength = readInt();
if (objectLength < 0) {
return null;
}
int end = MathUtils.addOrThrow(dataPosition(), objectLength);
int valueLength = end - start;
setDataPosition(end);
return new LazyValue(this, start, valueLength, type, loader);
} else {
return readValue(type, loader, /* clazz */ null);
}
}
private static final class LazyValue implements BiFunction<Class<?>, Class<?>[], Object> {
/**
* | 4B | 4B |
* mSource = Parcel{... | type | length | object | ...}
* a b c d
* length = d - c
* mPosition = a
* mLength = d - a
*/
private final int mPosition;
private final int mLength;
private final int mType;
@Nullable private final ClassLoader mLoader;
@Nullable private Object mObject;
/**
* This goes from non-null to null once. Always check the nullability of this object before
* performing any operations, either involving itself or mObject since the happens-before
* established by this volatile will guarantee visibility of either. We can assume this
* parcel won't change anymore.
*/
@Nullable private volatile Parcel mSource;
LazyValue(Parcel source, int position, int length, int type, @Nullable ClassLoader loader) {
mSource = requireNonNull(source);
mPosition = position;
mLength = length;
mType = type;
mLoader = loader;
}
@Override
public Object apply(@Nullable Class<?> clazz, @Nullable Class<?>[] itemTypes) {
Parcel source = mSource;
if (source != null) {
synchronized (source) {
// Check mSource != null guarantees callers won't ever see different objects.
if (mSource != null) {
int restore = source.dataPosition();
try {
source.setDataPosition(mPosition);
mObject = source.readValue(mLoader, clazz, itemTypes);
} finally {
source.setDataPosition(restore);
}
mSource = null;
}
}
}
return mObject;
}
public void writeToParcel(Parcel out) {
Parcel source = mSource;
if (source != null) {
out.appendFrom(source, mPosition, mLength);
} else {
out.writeValue(mObject);
}
}
public boolean hasFileDescriptors() {
Parcel source = mSource;
return (source != null)
? source.hasFileDescriptors(mPosition, mLength)
: Parcel.hasFileDescriptors(mObject);
}
@Override
public String toString() {
return (mSource != null)
? "Supplier{" + valueTypeToString(mType) + "@" + mPosition + "+" + mLength + '}'
: "Supplier{" + mObject + "}";
}
/**
* We're checking if the *lazy value* is equal to another one, not if the *object*
* represented by the lazy value is equal to the other one. So, if there are two lazy values
* and one of them has been deserialized but the other hasn't this will always return false.
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof LazyValue)) {
return false;
}
LazyValue value = (LazyValue) other;
// Check if they are either both serialized or both deserialized.
Parcel source = mSource;
Parcel otherSource = value.mSource;
if ((source == null) != (otherSource == null)) {
return false;
}
// If both are deserialized, compare the live objects.
if (source == null) {
// Note that here it's guaranteed that both mObject references contain valid values
// (possibly null) since mSource will have provided the memory barrier for those and
// once deserialized we never go back to serialized state.
return Objects.equals(mObject, value.mObject);
}
// Better safely fail here since this could mean we get different objects.
if (!Objects.equals(mLoader, value.mLoader)) {
return false;
}
// Otherwise compare metadata prior to comparing payload.
if (mType != value.mType || mLength != value.mLength) {
return false;
}
// Finally we compare the payload.
return Parcel.compareData(source, mPosition, otherSource, value.mPosition, mLength);
}
@Override
public int hashCode() {
// Accessing mSource first to provide memory barrier for mObject
return Objects.hash(mSource == null, mObject, mLoader, mType, mLength);
}
}
/** Same as {@link #readValue(ClassLoader, Class, Class[])} without any item types. */
private <T> T readValue(int type, @Nullable ClassLoader loader, @Nullable Class<T> clazz) {
// Avoids allocating Class[0] array
return readValue(type, loader, clazz, (Class<?>[]) null);
}
/**
* Reads a value from the parcel of type {@code type}. Does NOT read the int representing the
* type first.
*
* @param clazz The type of the object expected or {@code null} for performing no checks.
* @param itemTypes If the value is a container, these represent the item types (eg. for a list
* it's the item type, for a map, it's the key type, followed by the value
* type).
*/
@SuppressWarnings("unchecked")
@Nullable
private <T> T readValue(int type, @Nullable ClassLoader loader, @Nullable Class<T> clazz,
@Nullable Class<?>... itemTypes) {
final Object object;
switch (type) {
case VAL_NULL:
object = null;
break;
case VAL_STRING:
object = readString();
break;
case VAL_INTEGER:
object = readInt();
break;
case VAL_MAP:
checkTypeToUnparcel(clazz, HashMap.class);
Class<?> keyType = ArrayUtils.getOrNull(itemTypes, 0);
Class<?> valueType = ArrayUtils.getOrNull(itemTypes, 1);
checkArgument((keyType == null) == (valueType == null));
object = readHashMapInternal(loader, keyType, valueType);
break;
case VAL_PARCELABLE:
object = readParcelableInternal(loader, clazz);
break;
case VAL_SHORT:
object = (short) readInt();
break;
case VAL_LONG:
object = readLong();
break;
case VAL_FLOAT:
object = readFloat();
break;
case VAL_DOUBLE:
object = readDouble();
break;
case VAL_BOOLEAN:
object = readInt() == 1;
break;
case VAL_CHARSEQUENCE:
object = readCharSequence();
break;
case VAL_LIST: {
checkTypeToUnparcel(clazz, ArrayList.class);
Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
object = readArrayListInternal(loader, itemType);
break;
}
case VAL_BOOLEANARRAY:
object = createBooleanArray();
break;
case VAL_BYTEARRAY:
object = createByteArray();
break;
case VAL_STRINGARRAY:
object = readStringArray();
break;
case VAL_CHARSEQUENCEARRAY:
object = readCharSequenceArray();
break;
case VAL_IBINDER:
object = readStrongBinder();
break;
case VAL_OBJECTARRAY: {
Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
checkArrayTypeToUnparcel(clazz, (itemType != null) ? itemType : Object.class);
object = readArrayInternal(loader, itemType);
break;
}
case VAL_INTARRAY:
object = createIntArray();
break;
case VAL_LONGARRAY:
object = createLongArray();
break;
case VAL_BYTE:
object = readByte();
break;
case VAL_SERIALIZABLE:
object = readSerializableInternal(loader, clazz);
break;
case VAL_PARCELABLEARRAY: {
Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
checkArrayTypeToUnparcel(clazz, (itemType != null) ? itemType : Parcelable.class);
object = readParcelableArrayInternal(loader, itemType);
break;
}
case VAL_SPARSEARRAY: {
checkTypeToUnparcel(clazz, SparseArray.class);
Class<?> itemType = ArrayUtils.getOrNull(itemTypes, 0);
object = readSparseArrayInternal(loader, itemType);
break;
}
case VAL_SPARSEBOOLEANARRAY:
object = readSparseBooleanArray();
break;
case VAL_BUNDLE:
object = readBundle(loader); // loading will be deferred
break;
case VAL_PERSISTABLEBUNDLE:
object = readPersistableBundle(loader);
break;
case VAL_SIZE:
object = readSize();
break;
case VAL_SIZEF:
object = readSizeF();
break;
case VAL_DOUBLEARRAY:
object = createDoubleArray();
break;
case VAL_CHAR:
object = (char) readInt();
break;
case VAL_SHORTARRAY:
object = createShortArray();
break;
case VAL_CHARARRAY:
object = createCharArray();
break;
case VAL_FLOATARRAY:
object = createFloatArray();
break;
default:
int off = dataPosition() - 4;
throw new BadParcelableException(
"Parcel " + this + ": Unmarshalling unknown type code " + type
+ " at offset " + off);
}
if (object != null && clazz != null && !clazz.isInstance(object)) {
throw new BadTypeParcelableException("Unparcelled object " + object
+ " is not an instance of required class " + clazz.getName()
+ " provided in the parameter");
}
return (T) object;
}
private boolean isLengthPrefixed(int type) {
// In general, we want custom types and containers of custom types to be length-prefixed,
// this allows clients (eg. Bundle) to skip their content during deserialization. The
// exception to this is Bundle, since Bundle is already length-prefixed and already copies
// the correspondent section of the parcel internally.
switch (type) {
case VAL_MAP:
case VAL_PARCELABLE:
case VAL_LIST:
case VAL_SPARSEARRAY:
case VAL_PARCELABLEARRAY:
case VAL_OBJECTARRAY:
case VAL_SERIALIZABLE:
return true;
default:
return false;
}
}
/**
* Checks that an array of type T[], where T is {@code componentTypeToUnparcel}, is a subtype of
* {@code requiredArrayType}.
*/
private void checkArrayTypeToUnparcel(@Nullable Class<?> requiredArrayType,
Class<?> componentTypeToUnparcel) {
if (requiredArrayType != null) {
// In Java 12, we could use componentTypeToUnparcel.arrayType() for the check
Class<?> requiredComponentType = requiredArrayType.getComponentType();
if (requiredComponentType == null) {
throw new BadTypeParcelableException(
"About to unparcel an array but type "
+ requiredArrayType.getCanonicalName()
+ " required by caller is not an array.");
}
checkTypeToUnparcel(requiredComponentType, componentTypeToUnparcel);
}
}
/**
* Checks that {@code typeToUnparcel} is a subtype of {@code requiredType}, if {@code
* requiredType} is not {@code null}.
*/
private void checkTypeToUnparcel(@Nullable Class<?> requiredType, Class<?> typeToUnparcel) {
if (requiredType != null && !requiredType.isAssignableFrom(typeToUnparcel)) {
throw new BadTypeParcelableException(
"About to unparcel a " + typeToUnparcel.getCanonicalName()
+ ", which is not a subtype of type " + requiredType.getCanonicalName()
+ " required by caller.");
}
}
/**
* Read and return a new Parcelable from the parcel. The given class loader
* will be used to load any enclosed Parcelables. If it is null, the default
* class loader will be used.
* @param loader A ClassLoader from which to instantiate the Parcelable
* object, or null for the default class loader.
* @return Returns the newly created Parcelable, or null if a null
* object has been written.
* @throws BadParcelableException Throws BadParcelableException if there
* was an error trying to instantiate the Parcelable.
*
* @deprecated Use the type-safer version {@link #readParcelable(ClassLoader, Class)} starting
* from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the format to
* use {@link Parcelable.Creator#createFromParcel(Parcel)} if possible since this is also
* more performant. Note that changing to the latter also requires changing the writes.
*/
@Deprecated
@Nullable
public final <T extends Parcelable> T readParcelable(@Nullable ClassLoader loader) {
return readParcelableInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readParcelable(ClassLoader)} but accepts {@code clazz} parameter as the type
* required for each item.
*
* <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readParcelable(ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@Nullable
public <T> T readParcelable(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
Objects.requireNonNull(clazz);
return readParcelableInternal(loader, clazz);
}
/**
* @param clazz The type of the parcelable expected or {@code null} for performing no checks.
*/
@SuppressWarnings("unchecked")
@Nullable
private <T> T readParcelableInternal(@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
Parcelable.Creator<?> creator = readParcelableCreatorInternal(loader, clazz);
if (creator == null) {
return null;
}
if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
Parcelable.ClassLoaderCreator<?> classLoaderCreator =
(Parcelable.ClassLoaderCreator<?>) creator;
return (T) classLoaderCreator.createFromParcel(this, loader);
}
return (T) creator.createFromParcel(this);
}
/** @hide */
@UnsupportedAppUsage
@SuppressWarnings("unchecked")
@Nullable
public final <T extends Parcelable> T readCreator(@NonNull Parcelable.Creator<?> creator,
@Nullable ClassLoader loader) {
if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
Parcelable.ClassLoaderCreator<?> classLoaderCreator =
(Parcelable.ClassLoaderCreator<?>) creator;
return (T) classLoaderCreator.createFromParcel(this, loader);
}
return (T) creator.createFromParcel(this);
}
/**
* Read and return a Parcelable.Creator from the parcel. The given class loader will be used to
* load the {@link Parcelable.Creator}. If it is null, the default class loader will be used.
*
* @param loader A ClassLoader from which to instantiate the {@link Parcelable.Creator}
* object, or null for the default class loader.
* @return the previously written {@link Parcelable.Creator}, or null if a null Creator was
* written.
* @throws BadParcelableException Throws BadParcelableException if there was an error trying to
* read the {@link Parcelable.Creator}.
*
* @see #writeParcelableCreator
*
* @deprecated Use the type-safer version {@link #readParcelableCreator(ClassLoader, Class)}
* starting from Android {@link Build.VERSION_CODES#TIRAMISU}.
*/
@Deprecated
@Nullable
public final Parcelable.Creator<?> readParcelableCreator(@Nullable ClassLoader loader) {
return readParcelableCreatorInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readParcelableCreator(ClassLoader)} but accepts {@code clazz} parameter
* as the required type.
*
* <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readParcelableCreator(ClassLoader) instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there there was an error
* trying to read the {@link Parcelable.Creator}.
*/
@Nullable
public <T> Parcelable.Creator<T> readParcelableCreator(
@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
Objects.requireNonNull(clazz);
return readParcelableCreatorInternal(loader, clazz);
}
/**
* @param clazz The type of the parcelable expected or {@code null} for performing no checks.
*/
@SuppressWarnings("unchecked")
@Nullable
private <T> Parcelable.Creator<T> readParcelableCreatorInternal(
@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
String name = readString();
if (name == null) {
return null;
}
Pair<Parcelable.Creator<?>, Class<?>> creatorAndParcelableClass;
synchronized (sPairedCreators) {
HashMap<String, Pair<Parcelable.Creator<?>, Class<?>>> map =
sPairedCreators.get(loader);
if (map == null) {
sPairedCreators.put(loader, new HashMap<>());
mCreators.put(loader, new HashMap<>());
creatorAndParcelableClass = null;
} else {
creatorAndParcelableClass = map.get(name);
}
}
if (creatorAndParcelableClass != null) {
Parcelable.Creator<?> creator = creatorAndParcelableClass.first;
Class<?> parcelableClass = creatorAndParcelableClass.second;
if (clazz != null) {
if (!clazz.isAssignableFrom(parcelableClass)) {
throw new BadTypeParcelableException("Parcelable creator " + name + " is not "
+ "a subclass of required class " + clazz.getName()
+ " provided in the parameter");
}
}
return (Parcelable.Creator<T>) creator;
}
Parcelable.Creator<?> creator;
Class<?> parcelableClass;
try {
// If loader == null, explicitly emulate Class.forName(String) "caller
// classloader" behavior.
ClassLoader parcelableClassLoader =
(loader == null ? getClass().getClassLoader() : loader);
// Avoid initializing the Parcelable class until we know it implements
// Parcelable and has the necessary CREATOR field. http://b/1171613.
parcelableClass = Class.forName(name, false /* initialize */,
parcelableClassLoader);
if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
throw new BadParcelableException("Parcelable protocol requires subclassing "
+ "from Parcelable on class " + name);
}
if (clazz != null) {
if (!clazz.isAssignableFrom(parcelableClass)) {
throw new BadTypeParcelableException("Parcelable creator " + name + " is not "
+ "a subclass of required class " + clazz.getName()
+ " provided in the parameter");
}
}
Field f = parcelableClass.getField("CREATOR");
if ((f.getModifiers() & Modifier.STATIC) == 0) {
throw new BadParcelableException("Parcelable protocol requires "
+ "the CREATOR object to be static on class " + name);
}
Class<?> creatorType = f.getType();
if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
// Fail before calling Field.get(), not after, to avoid initializing
// parcelableClass unnecessarily.
throw new BadParcelableException("Parcelable protocol requires a "
+ "Parcelable.Creator object called "
+ "CREATOR on class " + name);
}
creator = (Parcelable.Creator<?>) f.get(null);
} catch (IllegalAccessException e) {
Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
throw new BadParcelableException(
"IllegalAccessException when unmarshalling: " + name, e);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Class not found when unmarshalling: " + name, e);
throw new BadParcelableException(
"ClassNotFoundException when unmarshalling: " + name, e);
} catch (NoSuchFieldException e) {
throw new BadParcelableException("Parcelable protocol requires a "
+ "Parcelable.Creator object called "
+ "CREATOR on class " + name, e);
}
if (creator == null) {
throw new BadParcelableException("Parcelable protocol requires a "
+ "non-null Parcelable.Creator object called "
+ "CREATOR on class " + name);
}
synchronized (sPairedCreators) {
sPairedCreators.get(loader).put(name, Pair.create(creator, parcelableClass));
mCreators.get(loader).put(name, creator);
}
return (Parcelable.Creator<T>) creator;
}
/**
* Read and return a new Parcelable array from the parcel.
* The given class loader will be used to load any enclosed
* Parcelables.
* @return the Parcelable array, or null if the array is null
*
* @deprecated Use the type-safer version {@link #readParcelableArray(ClassLoader, Class)}
* starting from Android {@link Build.VERSION_CODES#TIRAMISU}. Also consider changing the
* format to use {@link #createTypedArray(Parcelable.Creator)} if possible (eg. if the
* items' class is final) since this is also more performant. Note that changing to the
* latter also requires changing the writes.
*/
@Deprecated
@Nullable
public Parcelable[] readParcelableArray(@Nullable ClassLoader loader) {
return readParcelableArrayInternal(loader, /* clazz */ null);
}
/**
* Same as {@link #readParcelableArray(ClassLoader)} but accepts {@code clazz} parameter as
* the type required for each item.
*
* <p><b>Warning: </b> the class that implements {@link Parcelable} has to be the immediately
* enclosing class of the runtime type of its CREATOR field (that is,
* {@link Class#getEnclosingClass()} has to return the parcelable implementing class),
* otherwise this method might throw an exception. If the Parcelable class does not enclose the
* CREATOR, use the deprecated {@link #readParcelableArray(ClassLoader)} instead.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children classes or there was an error
* trying to instantiate an element.
*/
@SuppressLint({"ArrayReturn", "NullableCollection"})
@Nullable
public <T> T[] readParcelableArray(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
return readParcelableArrayInternal(loader, requireNonNull(clazz));
}
@SuppressWarnings("unchecked")
@Nullable
private <T> T[] readParcelableArrayInternal(@Nullable ClassLoader loader,
@Nullable Class<T> clazz) {
int n = readInt();
if (n < 0) {
return null;
}
T[] p = (T[]) ((clazz == null) ? new Parcelable[n] : Array.newInstance(clazz, n));
for (int i = 0; i < n; i++) {
p[i] = readParcelableInternal(loader, clazz);
}
return p;
}
/**
* Read and return a new Serializable object from the parcel.
* @return the Serializable object, or null if the Serializable name
* wasn't found in the parcel.
*
* Unlike {@link #readSerializable(ClassLoader, Class)}, it uses the nearest valid class loader
* up the execution stack to instantiate the Serializable object.
*
* @deprecated Use the type-safer version {@link #readSerializable(ClassLoader, Class)} starting
* from Android {@link Build.VERSION_CODES#TIRAMISU}.
*/
@Deprecated
@Nullable
public Serializable readSerializable() {
return readSerializableInternal(/* loader */ null, /* clazz */ null);
}
/**
* Same as {@link #readSerializable()} but accepts {@code loader} and {@code clazz} parameters.
*
* @param loader A ClassLoader from which to instantiate the Serializable object,
* or null for the default class loader.
* @param clazz The type of the object expected.
*
* @throws BadParcelableException Throws BadParcelableException if the item to be deserialized
* is not an instance of that class or any of its children class or there there was an error
* deserializing the object.
*/
@Nullable
public <T> T readSerializable(@Nullable ClassLoader loader, @NonNull Class<T> clazz) {
Objects.requireNonNull(clazz);
return readSerializableInternal(
loader == null ? getClass().getClassLoader() : loader, clazz);
}
/**
* @param clazz The type of the serializable expected or {@code null} for performing no checks
*/
@Nullable
private <T> T readSerializableInternal(@Nullable final ClassLoader loader,
@Nullable Class<T> clazz) {
String name = readString();
if (name == null) {
// For some reason we were unable to read the name of the Serializable (either there
// is nothing left in the Parcel to read, or the next value wasn't a String), so
// return null, which indicates that the name wasn't found in the parcel.
return null;
}
try {
if (clazz != null && loader != null) {
// If custom classloader is provided, resolve the type of serializable using the
// name, then check the type before deserialization. As in this case we can resolve
// the class the same way as ObjectInputStream, using the provided classloader.
Class<?> cl = Class.forName(name, false, loader);
if (!clazz.isAssignableFrom(cl)) {
throw new BadTypeParcelableException("Serializable object "
+ cl.getName() + " is not a subclass of required class "
+ clazz.getName() + " provided in the parameter");
}
}
byte[] serializedData = createByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
ObjectInputStream ois = new ObjectInputStream(bais) {
@Override
protected Class<?> resolveClass(ObjectStreamClass osClass)
throws IOException, ClassNotFoundException {
// try the custom classloader if provided
if (loader != null) {
Class<?> c = Class.forName(osClass.getName(), false, loader);
return Objects.requireNonNull(c);
}
return super.resolveClass(osClass);
}
};
T object = (T) ois.readObject();
if (clazz != null && loader == null) {
// If custom classloader is not provided, check the type of the serializable using
// the deserialized object, as we cannot resolve the class the same way as
// ObjectInputStream.
if (!clazz.isAssignableFrom(object.getClass())) {
throw new BadTypeParcelableException("Serializable object "
+ object.getClass().getName() + " is not a subclass of required class "
+ clazz.getName() + " provided in the parameter");
}
}
return object;
} catch (IOException ioe) {
throw new BadParcelableException("Parcelable encountered "
+ "IOException reading a Serializable object (name = "
+ name + ")", ioe);
} catch (ClassNotFoundException cnfe) {
throw new BadParcelableException("Parcelable encountered "
+ "ClassNotFoundException reading a Serializable object (name = "
+ name + ")", cnfe);
}
}
// Left due to the UnsupportedAppUsage. Do not use anymore - use sPairedCreators instead
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private static final HashMap<ClassLoader, HashMap<String, Parcelable.Creator<?>>>
mCreators = new HashMap<>();
// Cache of previously looked up CREATOR.createFromParcel() methods for particular classes.
// Keys are the names of the classes, values are a pair consisting of a parcelable creator,
// and the class of the parcelable type for the object.
private static final HashMap<ClassLoader, HashMap<String,
Pair<Parcelable.Creator<?>, Class<?>>>> sPairedCreators = new HashMap<>();
/** @hide for internal use only. */
static protected final Parcel obtain(int obj) {
throw new UnsupportedOperationException();
}
/** @hide */
static protected final Parcel obtain(long obj) {
Parcel res = null;
synchronized (sPoolSync) {
if (sHolderPool != null) {
res = sHolderPool;
sHolderPool = res.mPoolNext;
res.mPoolNext = null;
sHolderPoolSize--;
}
}
// When no cache found above, create from scratch; otherwise prepare the
// cached object to be used
if (res == null) {
res = new Parcel(obj);
} else {
res.mRecycled = false;
if (DEBUG_RECYCLE) {
res.mStack = new RuntimeException();
}
res.init(obj);
}
return res;
}
private Parcel(long nativePtr) {
if (DEBUG_RECYCLE) {
mStack = new RuntimeException();
}
//Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
init(nativePtr);
}
private void init(long nativePtr) {
if (nativePtr != 0) {
mNativePtr = nativePtr;
mOwnsNativeParcelObject = false;
} else {
mNativePtr = nativeCreate();
mOwnsNativeParcelObject = true;
}
}
private void freeBuffer() {
mFlags = 0;
resetSqaushingState();
if (mOwnsNativeParcelObject) {
nativeFreeBuffer(mNativePtr);
}
mReadWriteHelper = ReadWriteHelper.DEFAULT;
}
private void destroy() {
resetSqaushingState();
if (mNativePtr != 0) {
if (mOwnsNativeParcelObject) {
nativeDestroy(mNativePtr);
}
mNativePtr = 0;
}
}
@Override
protected void finalize() throws Throwable {
if (DEBUG_RECYCLE) {
// we could always have this log on, but it's spammy
if (!mRecycled) {
Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
}
}
destroy();
}
/**
* To be replaced by {@link #readMapInternal(Map, int, ClassLoader, Class, Class)}, but keep
* the old API for compatibility usages.
*/
/* package */ void readMapInternal(@NonNull Map outVal, int n,
@Nullable ClassLoader loader) {
readMapInternal(outVal, n, loader, /* clazzKey */null, /* clazzValue */null);
}
@Nullable
private <K, V> HashMap<K, V> readHashMapInternal(@Nullable ClassLoader loader,
@NonNull Class<? extends K> clazzKey, @NonNull Class<? extends V> clazzValue) {
int n = readInt();
if (n < 0) {
return null;
}
HashMap<K, V> map = new HashMap<>(n);
readMapInternal(map, n, loader, clazzKey, clazzValue);
return map;
}
private <K, V> void readMapInternal(@NonNull Map<? super K, ? super V> outVal,
@Nullable ClassLoader loader, @Nullable Class<K> clazzKey,
@Nullable Class<V> clazzValue) {
int n = readInt();
readMapInternal(outVal, n, loader, clazzKey, clazzValue);
}
private <K, V> void readMapInternal(@NonNull Map<? super K, ? super V> outVal, int n,
@Nullable ClassLoader loader, @Nullable Class<K> clazzKey,
@Nullable Class<V> clazzValue) {
while (n > 0) {
K key = readValue(loader, clazzKey);
V value = readValue(loader, clazzValue);
outVal.put(key, value);
n--;
}
}
private void readArrayMapInternal(@NonNull ArrayMap<? super String, Object> outVal,
int size, @Nullable ClassLoader loader) {
readArrayMap(outVal, size, /* sorted */ true, /* lazy */ false, loader);
}
/**
* Reads a map into {@code map}.
*
* @param sorted Whether the keys are sorted by their hashes, if so we use an optimized path.
* @param lazy Whether to populate the map with lazy {@link Supplier} objects for
* length-prefixed values. See {@link Parcel#readLazyValue(ClassLoader)} for more
* details.
* @return whether the parcel can be recycled or not.
* @hide
*/
boolean readArrayMap(ArrayMap<? super String, Object> map, int size, boolean sorted,
boolean lazy, @Nullable ClassLoader loader) {
boolean recycle = true;
while (size > 0) {
String key = readString();
Object value = (lazy) ? readLazyValue(loader) : readValue(loader);
if (value instanceof LazyValue) {
recycle = false;
}
if (sorted) {
map.append(key, value);
} else {
map.put(key, value);
}
size--;
}
if (sorted) {
map.validate();
}
return recycle;
}
/**
* @hide For testing only.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void readArrayMap(@NonNull ArrayMap<? super String, Object> outVal,
@Nullable ClassLoader loader) {
final int N = readInt();
if (N < 0) {
return;
}
readArrayMapInternal(outVal, N, loader);
}
/**
* Reads an array set.
*
* @param loader The class loader to use.
*
* @hide
*/
@UnsupportedAppUsage
public @Nullable ArraySet<? extends Object> readArraySet(@Nullable ClassLoader loader) {
final int size = readInt();
if (size < 0) {
return null;
}
ArraySet<Object> result = new ArraySet<>(size);
for (int i = 0; i < size; i++) {
Object value = readValue(loader);
result.append(value);
}
return result;
}
/**
* The method is replaced by {@link #readListInternal(List, int, ClassLoader, Class)}, however
* we are keeping this unused method here to allow unsupported app usages.
*/
private void readListInternal(@NonNull List outVal, int n, @Nullable ClassLoader loader) {
readListInternal(outVal, n, loader, /* clazz */ null);
}
/**
* @param clazz The type of the object expected or {@code null} for performing no checks.
*/
private <T> void readListInternal(@NonNull List<? super T> outVal, int n,
@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
while (n > 0) {
T value = readValue(loader, clazz);
//Log.d(TAG, "Unmarshalling value=" + value);
outVal.add(value);
n--;
}
}
/**
* @param clazz The type of the object expected or {@code null} for performing no checks.
*/
@SuppressLint({"ConcreteCollection", "NullableCollection"})
@Nullable
private <T> ArrayList<T> readArrayListInternal(@Nullable ClassLoader loader,
@Nullable Class<? extends T> clazz) {
int n = readInt();
if (n < 0) {
return null;
}
ArrayList<T> l = new ArrayList<>(n);
readListInternal(l, n, loader, clazz);
return l;
}
/**
* The method is replaced by {@link #readArrayInternal(ClassLoader, Class)}, however
* we are keeping this unused method here to allow unsupported app usages.
*/
private void readArrayInternal(@NonNull Object[] outVal, int N,
@Nullable ClassLoader loader) {
for (int i = 0; i < N; i++) {
Object value = readValue(loader, /* clazz */ null);
outVal[i] = value;
}
}
/**
* @param clazz The type of the object expected or {@code null} for performing no checks.
*/
@SuppressWarnings("unchecked")
@Nullable
private <T> T[] readArrayInternal(@Nullable ClassLoader loader, @Nullable Class<T> clazz) {
int n = readInt();
if (n < 0) {
return null;
}
T[] outVal = (T[]) ((clazz == null) ? new Object[n] : Array.newInstance(clazz, n));
for (int i = 0; i < n; i++) {
T value = readValue(loader, clazz);
outVal[i] = value;
}
return outVal;
}
/**
* The method is replaced by {@link #readSparseArray(ClassLoader, Class)}, however
* we are keeping this unused method here to allow unsupported app usages.
*/
private void readSparseArrayInternal(@NonNull SparseArray outVal, int N,
@Nullable ClassLoader loader) {
while (N > 0) {
int key = readInt();
Object value = readValue(loader);
outVal.append(key, value);
N--;
}
}
/**
* @param clazz The type of the object expected or {@code null} for performing no checks.
*/
@Nullable
private <T> SparseArray<T> readSparseArrayInternal(@Nullable ClassLoader loader,
@Nullable Class<? extends T> clazz) {
int n = readInt();
if (n < 0) {
return null;
}
SparseArray<T> outVal = new SparseArray<>(n);
while (n > 0) {
int key = readInt();
T value = readValue(loader, clazz);
outVal.append(key, value);
n--;
}
return outVal;
}
private void readSparseBooleanArrayInternal(@NonNull SparseBooleanArray outVal, int N) {
while (N > 0) {
int key = readInt();
boolean value = this.readByte() == 1;
//Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
outVal.append(key, value);
N--;
}
}
private void readSparseIntArrayInternal(@NonNull SparseIntArray outVal, int N) {
while (N > 0) {
int key = readInt();
int value = readInt();
outVal.append(key, value);
N--;
}
}
/**
* @hide For testing
*/
public long getOpenAshmemSize() {
return nativeGetOpenAshmemSize(mNativePtr);
}
private static String valueTypeToString(int type) {
switch (type) {
case VAL_NULL: return "VAL_NULL";
case VAL_INTEGER: return "VAL_INTEGER";
case VAL_MAP: return "VAL_MAP";
case VAL_BUNDLE: return "VAL_BUNDLE";
case VAL_PERSISTABLEBUNDLE: return "VAL_PERSISTABLEBUNDLE";
case VAL_PARCELABLE: return "VAL_PARCELABLE";
case VAL_SHORT: return "VAL_SHORT";
case VAL_LONG: return "VAL_LONG";
case VAL_FLOAT: return "VAL_FLOAT";
case VAL_DOUBLE: return "VAL_DOUBLE";
case VAL_BOOLEAN: return "VAL_BOOLEAN";
case VAL_CHARSEQUENCE: return "VAL_CHARSEQUENCE";
case VAL_LIST: return "VAL_LIST";
case VAL_SPARSEARRAY: return "VAL_SPARSEARRAY";
case VAL_BOOLEANARRAY: return "VAL_BOOLEANARRAY";
case VAL_BYTEARRAY: return "VAL_BYTEARRAY";
case VAL_STRINGARRAY: return "VAL_STRINGARRAY";
case VAL_CHARSEQUENCEARRAY: return "VAL_CHARSEQUENCEARRAY";
case VAL_IBINDER: return "VAL_IBINDER";
case VAL_PARCELABLEARRAY: return "VAL_PARCELABLEARRAY";
case VAL_INTARRAY: return "VAL_INTARRAY";
case VAL_LONGARRAY: return "VAL_LONGARRAY";
case VAL_BYTE: return "VAL_BYTE";
case VAL_SIZE: return "VAL_SIZE";
case VAL_SIZEF: return "VAL_SIZEF";
case VAL_DOUBLEARRAY: return "VAL_DOUBLEARRAY";
case VAL_CHAR: return "VAL_CHAR";
case VAL_SHORTARRAY: return "VAL_SHORTARRAY";
case VAL_CHARARRAY: return "VAL_CHARARRAY";
case VAL_FLOATARRAY: return "VAL_FLOATARRAY";
case VAL_OBJECTARRAY: return "VAL_OBJECTARRAY";
case VAL_SERIALIZABLE: return "VAL_SERIALIZABLE";
default: return "UNKNOWN(" + type + ")";
}
}
}
|