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
|
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "fastboot.h"
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
#include <functional>
#include <iostream>
#include <memory>
#include <regex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <android-base/endian.h>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <android-base/parseint.h>
#include <android-base/parsenetaddress.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <libavb/libavb.h>
#include <liblp/liblp.h>
#include <liblp/super_layout_builder.h>
#include <sparse/sparse.h>
#include <ziparchive/zip_archive.h>
#include "bootimg_utils.h"
#include "constants.h"
#include "diagnose_usb.h"
#include "fastboot_driver.h"
#include "fastboot_driver_interface.h"
#include "fs.h"
#include "storage.h"
#include "task.h"
#include "tcp.h"
#include "transport.h"
#include "udp.h"
#include "usb.h"
#include "util.h"
#include "vendor_boot_img_utils.h"
using android::base::borrowed_fd;
using android::base::ReadFully;
using android::base::Split;
using android::base::Trim;
using android::base::unique_fd;
using namespace std::placeholders;
#define FASTBOOT_INFO_VERSION 1
static const char* serial = nullptr;
static bool g_long_listing = false;
// Don't resparse files in too-big chunks.
// libsparse will support INT_MAX, but this results in large allocations, so
// let's keep it at 1GB to avoid memory pressure on the host.
static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
static int64_t target_sparse_limit = -1;
static unsigned g_base_addr = 0x10000000;
static boot_img_hdr_v2 g_boot_img_hdr = {};
static std::string g_cmdline;
static std::string g_dtb_path;
static bool g_disable_verity = false;
static bool g_disable_verification = false;
fastboot::FastBootDriver* fb = nullptr;
static std::vector<Image> images = {
// clang-format off
{ "boot", "boot.img", "boot.sig", "boot", false, ImageType::BootCritical },
{ "bootloader",
"bootloader.img", "", "bootloader",
true, ImageType::Extra },
{ "init_boot",
"init_boot.img", "init_boot.sig",
"init_boot",
true, ImageType::BootCritical },
{ "", "boot_other.img", "boot.sig", "boot", true, ImageType::Normal },
{ "cache", "cache.img", "cache.sig", "cache", true, ImageType::Extra },
{ "dtbo", "dtbo.img", "dtbo.sig", "dtbo", true, ImageType::BootCritical },
{ "dts", "dt.img", "dt.sig", "dts", true, ImageType::BootCritical },
{ "odm", "odm.img", "odm.sig", "odm", true, ImageType::Normal },
{ "odm_dlkm", "odm_dlkm.img", "odm_dlkm.sig", "odm_dlkm", true, ImageType::Normal },
{ "product", "product.img", "product.sig", "product", true, ImageType::Normal },
{ "pvmfw", "pvmfw.img", "pvmfw.sig", "pvmfw", true, ImageType::BootCritical },
{ "radio", "radio.img", "", "radio", true, ImageType::Extra },
{ "recovery", "recovery.img", "recovery.sig", "recovery", true, ImageType::BootCritical },
{ "super", "super.img", "super.sig", "super", true, ImageType::Extra },
{ "system", "system.img", "system.sig", "system", false, ImageType::Normal },
{ "system_dlkm",
"system_dlkm.img", "system_dlkm.sig",
"system_dlkm",
true, ImageType::Normal },
{ "system_ext",
"system_ext.img", "system_ext.sig",
"system_ext",
true, ImageType::Normal },
{ "", "system_other.img", "system.sig", "system", true, ImageType::Normal },
{ "userdata", "userdata.img", "userdata.sig", "userdata", true, ImageType::Extra },
{ "vbmeta", "vbmeta.img", "vbmeta.sig", "vbmeta", true, ImageType::BootCritical },
{ "vbmeta_system",
"vbmeta_system.img",
"vbmeta_system.sig",
"vbmeta_system",
true, ImageType::BootCritical },
{ "vbmeta_vendor",
"vbmeta_vendor.img",
"vbmeta_vendor.sig",
"vbmeta_vendor",
true, ImageType::BootCritical },
{ "vendor", "vendor.img", "vendor.sig", "vendor", true, ImageType::Normal },
{ "vendor_boot",
"vendor_boot.img", "vendor_boot.sig",
"vendor_boot",
true, ImageType::BootCritical },
{ "vendor_dlkm",
"vendor_dlkm.img", "vendor_dlkm.sig",
"vendor_dlkm",
true, ImageType::Normal },
{ "vendor_kernel_boot",
"vendor_kernel_boot.img",
"vendor_kernel_boot.sig",
"vendor_kernel_boot",
true, ImageType::BootCritical },
{ "", "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
// clang-format on
};
char* get_android_product_out() {
char* dir = getenv("ANDROID_PRODUCT_OUT");
if (dir == nullptr || dir[0] == '\0') {
return nullptr;
}
return dir;
}
static std::string find_item_given_name(const std::string& img_name) {
char* dir = get_android_product_out();
if (!dir) {
die("ANDROID_PRODUCT_OUT not set");
}
return std::string(dir) + "/" + img_name;
}
std::string find_item(const std::string& item) {
for (size_t i = 0; i < images.size(); ++i) {
if (!images[i].nickname.empty() && item == images[i].nickname) {
return find_item_given_name(images[i].img_name);
}
}
fprintf(stderr, "unknown partition '%s'\n", item.c_str());
return "";
}
double last_start_time;
static void Status(const std::string& message) {
if (!message.empty()) {
static constexpr char kStatusFormat[] = "%-50s ";
fprintf(stderr, kStatusFormat, message.c_str());
}
last_start_time = now();
}
static void Epilog(int status) {
if (status) {
fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
die("Command failed");
} else {
double split = now();
fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
}
}
static void InfoMessage(const std::string& info) {
fprintf(stderr, "(bootloader) %s\n", info.c_str());
}
static void TextMessage(const std::string& text) {
fprintf(stderr, "%s", text.c_str());
}
bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
out->clear();
unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
if (fd == -1) {
return false;
}
out->resize(get_file_size(fd));
return ReadFully(fd, out->data(), out->size());
}
static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
return -1;
}
// require matching serial number or device path if requested
// at the command line with the -s option.
if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
strcmp(local_serial, info->device_path) != 0))
return -1;
return 0;
}
static ifc_match_func match_fastboot(const char* local_serial = serial) {
return [local_serial](usb_ifc_info* info) -> int {
return match_fastboot_with_serial(info, local_serial);
};
}
// output compatible with "adb devices"
static void PrintDevice(const char* local_serial, const char* status = nullptr,
const char* details = nullptr) {
if (local_serial == nullptr || strlen(local_serial) == 0) {
return;
}
if (g_long_listing) {
printf("%-22s", local_serial);
} else {
printf("%s\t", local_serial);
}
if (status != nullptr && strlen(status) > 0) {
printf(" %s", status);
}
if (g_long_listing) {
if (details != nullptr && strlen(details) > 0) {
printf(" %s", details);
}
}
putchar('\n');
}
static int list_devices_callback(usb_ifc_info* info) {
if (match_fastboot_with_serial(info, nullptr) == 0) {
std::string serial = info->serial_number;
std::string interface = info->interface;
if (interface.empty()) {
interface = "fastboot";
}
if (!info->writable) {
serial = UsbNoPermissionsShortHelpText();
}
if (!serial[0]) {
serial = "????????????";
}
PrintDevice(serial.c_str(), interface.c_str(), info->device_path);
}
return -1;
}
Result<NetworkSerial, FastbootError> ParseNetworkSerial(const std::string& serial) {
Socket::Protocol protocol;
const char* net_address = nullptr;
int port = 0;
if (android::base::StartsWith(serial, "tcp:")) {
protocol = Socket::Protocol::kTcp;
net_address = serial.c_str() + strlen("tcp:");
port = tcp::kDefaultPort;
} else if (android::base::StartsWith(serial, "udp:")) {
protocol = Socket::Protocol::kUdp;
net_address = serial.c_str() + strlen("udp:");
port = udp::kDefaultPort;
} else {
return Error<FastbootError>(FastbootError::Type::NETWORK_SERIAL_WRONG_PREFIX)
<< "protocol prefix ('tcp:' or 'udp:') is missed: " << serial << ". "
<< "Expected address format:\n"
<< "<protocol>:<address>:<port> (tcp:localhost:5554)";
}
std::string error;
std::string host;
if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
return Error<FastbootError>(FastbootError::Type::NETWORK_SERIAL_WRONG_ADDRESS)
<< "invalid network address '" << net_address << "': " << error;
}
return NetworkSerial{protocol, host, port};
}
// Opens a new Transport connected to the particular device.
// arguments:
//
// local_serial - device to connect (can be a network or usb serial name)
// wait_for_device - flag indicates whether we need to wait for device
// announce - flag indicates whether we need to print error to stdout in case
// we cannot connect to the device
//
// The returned Transport is a singleton, so multiple calls to this function will return the same
// object, and the caller should not attempt to delete the returned Transport.
static std::unique_ptr<Transport> open_device(const char* local_serial, bool wait_for_device = true,
bool announce = true) {
const Result<NetworkSerial, FastbootError> network_serial = ParseNetworkSerial(local_serial);
std::unique_ptr<Transport> transport;
while (true) {
if (network_serial.ok()) {
std::string error;
if (network_serial->protocol == Socket::Protocol::kTcp) {
transport = tcp::Connect(network_serial->address, network_serial->port, &error);
} else if (network_serial->protocol == Socket::Protocol::kUdp) {
transport = udp::Connect(network_serial->address, network_serial->port, &error);
}
if (!transport && announce) {
LOG(ERROR) << "error: " << error;
}
} else if (network_serial.error().code() ==
FastbootError::Type::NETWORK_SERIAL_WRONG_PREFIX) {
// WRONG_PREFIX is special because it happens when user wants to communicate with USB
// device
transport = usb_open(match_fastboot(local_serial));
} else {
Expect(network_serial);
}
if (transport) {
return transport;
}
if (!wait_for_device) {
return transport;
}
if (announce) {
announce = false;
LOG(ERROR) << "< waiting for " << local_serial << ">";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
static std::unique_ptr<Transport> NetworkDeviceConnected(bool print = false) {
std::unique_ptr<Transport> transport;
std::unique_ptr<Transport> result;
ConnectedDevicesStorage storage;
std::set<std::string> devices;
if (storage.Exists()) {
FileLock lock = storage.Lock();
devices = storage.ReadDevices(lock);
}
for (const std::string& device : devices) {
transport = open_device(device.c_str(), false, false);
if (print) {
PrintDevice(device.c_str(), transport ? "fastboot" : "offline");
}
if (transport) {
result = std::move(transport);
}
}
return result;
}
// Detects the fastboot connected device to open a new Transport.
// Detecting logic:
//
// if serial is provided - try to connect to this particular usb/network device
// othervise:
// 1. Check connected usb devices and return the last connected one
// 2. Check connected network devices and return the last connected one
// 2. If nothing is connected - wait for any device by repeating p. 1 and 2
//
// The returned Transport is a singleton, so multiple calls to this function will return the same
// object, and the caller should not attempt to delete the returned Transport.
static std::unique_ptr<Transport> open_device() {
if (serial != nullptr) {
return open_device(serial);
}
bool announce = true;
std::unique_ptr<Transport> transport;
while (true) {
transport = usb_open(match_fastboot(nullptr));
if (transport) {
return transport;
}
transport = NetworkDeviceConnected();
if (transport) {
return transport;
}
if (announce) {
announce = false;
LOG(ERROR) << "< waiting for any device >";
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return transport;
}
static int Connect(int argc, char* argv[]) {
if (argc != 1) {
LOG(FATAL) << "connect command requires to receive only 1 argument. Usage:" << std::endl
<< "fastboot connect [tcp:|udp:host:port]";
}
const char* local_serial = *argv;
Expect(ParseNetworkSerial(local_serial));
if (!open_device(local_serial, false)) {
return 1;
}
ConnectedDevicesStorage storage;
{
FileLock lock = storage.Lock();
std::set<std::string> devices = storage.ReadDevices(lock);
devices.insert(local_serial);
storage.WriteDevices(lock, devices);
}
return 0;
}
static int Disconnect(const char* local_serial) {
Expect(ParseNetworkSerial(local_serial));
ConnectedDevicesStorage storage;
{
FileLock lock = storage.Lock();
std::set<std::string> devices = storage.ReadDevices(lock);
devices.erase(local_serial);
storage.WriteDevices(lock, devices);
}
return 0;
}
static int Disconnect() {
ConnectedDevicesStorage storage;
{
FileLock lock = storage.Lock();
storage.Clear(lock);
}
return 0;
}
static int Disconnect(int argc, char* argv[]) {
switch (argc) {
case 0: {
return Disconnect();
}
case 1: {
return Disconnect(*argv);
}
default:
LOG(FATAL) << "disconnect command can receive only 0 or 1 arguments. Usage:"
<< std::endl
<< "fastboot disconnect # disconnect all devices" << std::endl
<< "fastboot disconnect [tcp:|udp:host:port] # disconnect device";
}
return 0;
}
static void list_devices() {
// We don't actually open a USB device here,
// just getting our callback called so we can
// list all the connected devices.
usb_open(list_devices_callback);
NetworkDeviceConnected(/* print */ true);
}
void syntax_error(const char* fmt, ...) {
fprintf(stderr, "fastboot: usage: ");
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
exit(1);
}
static int show_help() {
// clang-format off
fprintf(stdout,
// 1 2 3 4 5 6 7 8
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
"usage: fastboot [OPTION...] COMMAND...\n"
"\n"
"flashing:\n"
" update ZIP Flash all partitions from an update.zip package.\n"
" flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
" On A/B devices, flashed slot is set as active.\n"
" Secondary images may be flashed to inactive slot.\n"
" flash PARTITION [FILENAME] Flash given partition, using the image from\n"
" $ANDROID_PRODUCT_OUT if no filename is given.\n"
"\n"
"basics:\n"
" devices [-l] List devices in bootloader (-l: with device paths).\n"
" getvar NAME Display given bootloader variable.\n"
" reboot [bootloader] Reboot device.\n"
"\n"
"locking/unlocking:\n"
" flashing lock|unlock Lock/unlock partitions for flashing\n"
" flashing lock_critical|unlock_critical\n"
" Lock/unlock 'critical' bootloader partitions.\n"
" flashing get_unlock_ability\n"
" Check whether unlocking is allowed (1) or not(0).\n"
"\n"
"advanced:\n"
" erase PARTITION Erase a flash partition.\n"
" format[:FS_TYPE[:SIZE]] PARTITION\n"
" Format a flash partition.\n"
" set_active SLOT Set the active slot.\n"
" oem [COMMAND...] Execute OEM-specific command.\n"
" gsi wipe|disable|status Wipe, disable or show status of a GSI installation\n"
" (fastbootd only).\n"
" wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
" contain an empty set of default dynamic partitions.\n"
" create-logical-partition NAME SIZE\n"
" Create a logical partition with the given name and\n"
" size, in the super partition.\n"
" delete-logical-partition NAME\n"
" Delete a logical partition with the given name.\n"
" resize-logical-partition NAME SIZE\n"
" Change the size of the named logical partition.\n"
" snapshot-update cancel On devices that support snapshot-based updates, cancel\n"
" an in-progress update. This may make the device\n"
" unbootable until it is reflashed.\n"
" snapshot-update merge On devices that support snapshot-based updates, finish\n"
" an in-progress update if it is in the \"merging\"\n"
" phase.\n"
" fetch PARTITION OUT_FILE Fetch a partition image from the device."
"\n"
"boot image:\n"
" boot KERNEL [RAMDISK [SECOND]]\n"
" Download and boot kernel from RAM.\n"
" flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
" Create boot image and flash it.\n"
" --dtb DTB Specify path to DTB for boot image header version 2.\n"
" --cmdline CMDLINE Override kernel command line.\n"
" --base ADDRESS Set kernel base address (default: 0x10000000).\n"
" --kernel-offset Set kernel offset (default: 0x00008000).\n"
" --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
" --tags-offset Set tags offset (default: 0x00000100).\n"
" --dtb-offset Set dtb offset (default: 0x01100000).\n"
" --page-size BYTES Set flash page size (default: 2048).\n"
" --header-version VERSION Set boot image header version.\n"
" --os-version MAJOR[.MINOR[.PATCH]]\n"
" Set boot image OS version (default: 0.0.0).\n"
" --os-patch-level YYYY-MM-DD\n"
" Set boot image OS security patch level.\n"
// TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
"\n"
// TODO: what device(s) used this? is there any documentation?
//" continue Continue with autoboot.\n"
//"\n"
"Android Things:\n"
" stage IN_FILE Sends given file to stage for the next command.\n"
" get_staged OUT_FILE Writes data staged by the last command to a file.\n"
"\n"
"options:\n"
" -w Wipe userdata.\n"
" -s SERIAL Specify a USB device.\n"
" -s tcp|udp:HOST[:PORT] Specify a network device.\n"
" -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
" --force Force a flash operation that may be unsafe.\n"
" --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
" non-current slot (default: current active slot).\n"
" --set-active[=SLOT] Sets the active slot before rebooting.\n"
" --skip-secondary Don't flash secondary slots in flashall/update.\n"
" --skip-reboot Don't reboot device after flashing.\n"
" --disable-verity Sets disable-verity when flashing vbmeta.\n"
" --disable-verification Sets disable-verification when flashing vbmeta.\n"
" --disable-super-optimization\n"
" Disables optimizations on flashing super partition.\n"
" --disable-fastboot-info Will collects tasks from image list rather than $OUT/fastboot-info.txt.\n"
" --fs-options=OPTION[,OPTION]\n"
" Enable filesystem features. OPTION supports casefold, projid, compress\n"
// TODO: remove --unbuffered?
" --unbuffered Don't buffer input or output.\n"
" --verbose, -v Verbose output.\n"
" --version Display version.\n"
" --help, -h Show this message.\n"
);
// clang-format on
return 0;
}
static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
const std::string& second_stage) {
std::vector<char> kernel_data;
if (!ReadFileToVector(kernel, &kernel_data)) {
die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
}
// Is this actually a boot image?
if (kernel_data.size() < sizeof(boot_img_hdr_v3)) {
die("cannot load '%s': too short", kernel.c_str());
}
if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
if (!g_cmdline.empty()) {
bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
}
if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
return kernel_data;
}
std::vector<char> ramdisk_data;
if (!ramdisk.empty()) {
if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
}
}
std::vector<char> second_stage_data;
if (!second_stage.empty()) {
if (!ReadFileToVector(second_stage, &second_stage_data)) {
die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
}
}
std::vector<char> dtb_data;
if (!g_dtb_path.empty()) {
if (g_boot_img_hdr.header_version != 2) {
die("Argument dtb not supported for boot image header version %d\n",
g_boot_img_hdr.header_version);
}
if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
}
}
fprintf(stderr, "creating boot image...\n");
std::vector<char> out;
mkbootimg(kernel_data, ramdisk_data, second_stage_data, dtb_data, g_base_addr, g_boot_img_hdr,
&out);
if (!g_cmdline.empty()) {
bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(out.data()), g_cmdline);
}
fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
return out;
}
static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
std::vector<char>* out) {
ZipEntry64 zip_entry;
if (FindEntry(zip, entry_name, &zip_entry) != 0) {
fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
return false;
}
if (zip_entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
die("entry '%s' is too large: %" PRIu64, entry_name.c_str(), zip_entry.uncompressed_length);
}
out->resize(zip_entry.uncompressed_length);
fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
out->size() / 1024 / 1024);
int error =
ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()), out->size());
if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
return true;
}
#if defined(_WIN32)
// TODO: move this to somewhere it can be shared.
#include <windows.h>
// Windows' tmpfile(3) requires administrator rights because
// it creates temporary files in the root directory.
static FILE* win32_tmpfile() {
char temp_path[PATH_MAX];
DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
if (nchars == 0 || nchars >= sizeof(temp_path)) {
die("GetTempPath failed, error %ld", GetLastError());
}
char filename[PATH_MAX];
if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
die("GetTempFileName failed, error %ld", GetLastError());
}
return fopen(filename, "w+bTD");
}
#define tmpfile win32_tmpfile
static int make_temporary_fd(const char* /*what*/) {
// TODO: reimplement to avoid leaking a FILE*.
return fileno(tmpfile());
}
#else
static std::string make_temporary_template() {
const char* tmpdir = getenv("TMPDIR");
if (tmpdir == nullptr) tmpdir = P_tmpdir;
return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
}
static int make_temporary_fd(const char* what) {
std::string path_template(make_temporary_template());
int fd = mkstemp(&path_template[0]);
if (fd == -1) {
die("failed to create temporary file for %s with template %s: %s\n", path_template.c_str(),
what, strerror(errno));
}
unlink(path_template.c_str());
return fd;
}
#endif
static unique_fd UnzipToFile(ZipArchiveHandle zip, const char* entry_name) {
unique_fd fd(make_temporary_fd(entry_name));
ZipEntry64 zip_entry;
if (FindEntry(zip, entry_name, &zip_entry) != 0) {
fprintf(stderr, "archive does not contain '%s'\n", entry_name);
errno = ENOENT;
return unique_fd();
}
fprintf(stderr, "extracting %s (%" PRIu64 " MB) to disk...", entry_name,
zip_entry.uncompressed_length / 1024 / 1024);
double start = now();
int error = ExtractEntryToFile(zip, &zip_entry, fd.get());
if (error != 0) {
die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
}
if (lseek(fd.get(), 0, SEEK_SET) != 0) {
die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
}
fprintf(stderr, " took %.3fs\n", now() - start);
return fd;
}
static bool CheckRequirement(const std::string& cur_product, const std::string& var,
const std::string& product, bool invert,
const std::vector<std::string>& options) {
Status("Checking '" + var + "'");
double start = now();
if (!product.empty()) {
if (product != cur_product) {
double split = now();
fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
cur_product.c_str(), product.c_str(), (split - start));
return true;
}
}
std::string var_value;
if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
fprintf(stderr, "FAILED\n\n");
fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(), fb->Error().c_str());
return false;
}
bool match = false;
for (const auto& option : options) {
if (option == var_value ||
(option.back() == '*' &&
!var_value.compare(0, option.length() - 1, option, 0, option.length() - 1))) {
match = true;
break;
}
}
if (invert) {
match = !match;
}
if (match) {
double split = now();
fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
return true;
}
fprintf(stderr, "FAILED\n\n");
fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
for (auto it = std::next(options.begin()); it != options.end(); ++it) {
fprintf(stderr, " or '%s'", it->c_str());
}
fprintf(stderr, ".\n\n");
return false;
}
bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
bool* invert, std::vector<std::string>* options) {
// "require product=alpha|beta|gamma"
// "require version-bootloader=1234"
// "require-for-product:gamma version-bootloader=istanbul|constantinople"
// "require partition-exists=vendor"
*product = "";
*invert = false;
auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
auto require_product_regex =
std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
std::smatch match_results;
if (std::regex_match(line, match_results, require_reject_regex)) {
*invert = Trim(match_results[1]) == "reject";
} else if (std::regex_match(line, match_results, require_product_regex)) {
*product = match_results[1];
} else {
return false;
}
*name = match_results[2];
// Work around an unfortunate name mismatch.
if (*name == "board") {
*name = "product";
}
auto raw_options = Split(match_results[3], "|");
for (const auto& option : raw_options) {
auto trimmed_option = Trim(option);
options->emplace_back(trimmed_option);
}
return true;
}
// "require partition-exists=x" is a special case, added because of the trouble we had when
// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
// missing out new partitions. A device with new partitions can use "partition-exists" to
// override the fields `optional_if_no_image` in the `images` array.
static void HandlePartitionExists(const std::vector<std::string>& options) {
const std::string& partition_name = options[0];
std::string has_slot;
if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
(has_slot != "yes" && has_slot != "no")) {
die("device doesn't have required partition %s!", partition_name.c_str());
}
bool known_partition = false;
for (size_t i = 0; i < images.size(); ++i) {
if (!images[i].nickname.empty() && images[i].nickname == partition_name) {
images[i].optional_if_no_image = false;
known_partition = true;
}
}
if (!known_partition) {
die("device requires partition %s which is not known to this version of fastboot",
partition_name.c_str());
}
}
static void CheckRequirements(const std::string& data, bool force_flash) {
std::string cur_product;
if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
}
auto lines = Split(data, "\n");
for (const auto& line : lines) {
if (line.empty()) {
continue;
}
std::string name;
std::string product;
bool invert;
std::vector<std::string> options;
if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
continue;
}
if (name == "partition-exists") {
HandlePartitionExists(options);
} else {
bool met = CheckRequirement(cur_product, name, product, invert, options);
if (!met) {
if (!force_flash) {
die("requirements not met!");
} else {
fprintf(stderr, "requirements not met! but proceeding due to --force\n");
}
}
}
}
}
static void DisplayVarOrError(const std::string& label, const std::string& var) {
std::string value;
if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
Status("getvar:" + var);
fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
return;
}
fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
}
static void DumpInfo() {
fprintf(stderr, "--------------------------------------------\n");
DisplayVarOrError("Bootloader Version...", "version-bootloader");
DisplayVarOrError("Baseband Version.....", "version-baseband");
DisplayVarOrError("Serial Number........", "serialno");
fprintf(stderr, "--------------------------------------------\n");
}
std::vector<SparsePtr> resparse_file(sparse_file* s, int64_t max_size) {
if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
die("invalid max size %" PRId64, max_size);
}
const int files = sparse_file_resparse(s, max_size, nullptr, 0);
if (files < 0) die("Failed to compute resparse boundaries");
auto temp = std::make_unique<sparse_file*[]>(files);
const int rv = sparse_file_resparse(s, max_size, temp.get(), files);
if (rv < 0) die("Failed to resparse");
std::vector<SparsePtr> out_s;
for (int i = 0; i < files; i++) {
out_s.emplace_back(temp[i], sparse_file_destroy);
}
return out_s;
}
static std::vector<SparsePtr> load_sparse_files(int fd, int64_t max_size) {
SparsePtr s(sparse_file_import_auto(fd, false, true), sparse_file_destroy);
if (!s) die("cannot sparse read file");
return resparse_file(s.get(), max_size);
}
static uint64_t get_uint_var(const char* var_name, fastboot::IFastBootDriver* fb) {
std::string value_str;
if (fb->GetVar(var_name, &value_str) != fastboot::SUCCESS || value_str.empty()) {
verbose("target didn't report %s", var_name);
return 0;
}
// Some bootloaders (angler, for example) send spurious whitespace too.
value_str = android::base::Trim(value_str);
uint64_t value;
if (!android::base::ParseUint(value_str, &value)) {
fprintf(stderr, "couldn't parse %s '%s'\n", var_name, value_str.c_str());
return 0;
}
if (value > 0) verbose("target reported %s of %" PRId64 " bytes", var_name, value);
return value;
}
int64_t get_sparse_limit(int64_t size, const FlashingPlan* fp) {
int64_t limit = int64_t(fp->sparse_limit);
if (limit == 0) {
// Unlimited, so see what the target device's limit is.
// TODO: shouldn't we apply this limit even if you've used -S?
if (target_sparse_limit == -1) {
target_sparse_limit = static_cast<int64_t>(get_uint_var("max-download-size", fp->fb));
}
if (target_sparse_limit > 0) {
limit = target_sparse_limit;
} else {
return 0;
}
}
if (size > limit) {
return std::min(limit, RESPARSE_LIMIT);
}
return 0;
}
static bool load_buf_fd(unique_fd fd, struct fastboot_buffer* buf, const FlashingPlan* fp) {
int64_t sz = get_file_size(fd);
if (sz == -1) {
return false;
}
if (sparse_file* s = sparse_file_import(fd.get(), false, false)) {
buf->image_size = sparse_file_len(s, false, false);
if (buf->image_size < 0) {
LOG(ERROR) << "Could not compute length of sparse file";
return false;
}
sparse_file_destroy(s);
buf->file_type = FB_BUFFER_SPARSE;
} else {
buf->image_size = sz;
buf->file_type = FB_BUFFER_FD;
}
lseek(fd.get(), 0, SEEK_SET);
int64_t limit = get_sparse_limit(sz, fp);
buf->fd = std::move(fd);
if (limit) {
buf->files = load_sparse_files(buf->fd.get(), limit);
if (buf->files.empty()) {
return false;
}
buf->type = FB_BUFFER_SPARSE;
} else {
buf->type = FB_BUFFER_FD;
buf->sz = sz;
}
return true;
}
static bool load_buf(const char* fname, struct fastboot_buffer* buf, const FlashingPlan* fp) {
unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
if (fd == -1) {
return false;
}
struct stat s;
if (fstat(fd.get(), &s)) {
return false;
}
if (!S_ISREG(s.st_mode)) {
errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
return false;
}
return load_buf_fd(std::move(fd), buf, fp);
}
static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf, bool vbmeta_in_boot) {
// Buffer needs to be at least the size of the VBMeta struct which
// is 256 bytes.
if (buf->sz < 256) {
return;
}
std::string data;
if (!android::base::ReadFdToString(buf->fd, &data)) {
die("Failed reading from vbmeta");
}
uint64_t vbmeta_offset = 0;
if (vbmeta_in_boot) {
// Tries to locate top-level vbmeta from boot.img footer.
uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
die("Failed to find AVB_FOOTER at offset: %" PRId64 ", is BOARD_AVB_ENABLE true?",
footer_offset);
}
const AvbFooter* footer = reinterpret_cast<const AvbFooter*>(data.c_str() + footer_offset);
vbmeta_offset = be64toh(footer->vbmeta_offset);
}
// Ensures there is AVB_MAGIC at vbmeta_offset.
if (0 != data.compare(vbmeta_offset, AVB_MAGIC_LEN, AVB_MAGIC)) {
die("Failed to find AVB_MAGIC at offset: %" PRId64, vbmeta_offset);
}
fprintf(stderr, "Rewriting vbmeta struct at offset: %" PRId64 "\n", vbmeta_offset);
// There's a 32-bit big endian |flags| field at offset 120 where
// bit 0 corresponds to disable-verity and bit 1 corresponds to
// disable-verification.
//
// See external/avb/libavb/avb_vbmeta_image.h for the layout of
// the VBMeta struct.
uint64_t flags_offset = 123 + vbmeta_offset;
if (g_disable_verity) {
data[flags_offset] |= 0x01;
}
if (g_disable_verification) {
data[flags_offset] |= 0x02;
}
unique_fd fd(make_temporary_fd("vbmeta rewriting"));
if (!android::base::WriteStringToFd(data, fd)) {
die("Failed writing to modified vbmeta");
}
buf->fd = std::move(fd);
lseek(buf->fd.get(), 0, SEEK_SET);
}
static bool has_vbmeta_partition() {
std::string partition_type;
return fb->GetVar("partition-type:vbmeta", &partition_type) == fastboot::SUCCESS ||
fb->GetVar("partition-type:vbmeta_a", &partition_type) == fastboot::SUCCESS ||
fb->GetVar("partition-type:vbmeta_b", &partition_type) == fastboot::SUCCESS;
}
static bool is_vbmeta_partition(const std::string& partition) {
return android::base::EndsWith(partition, "vbmeta") ||
android::base::EndsWith(partition, "vbmeta_a") ||
android::base::EndsWith(partition, "vbmeta_b");
}
// Note: this only works in userspace fastboot. In the bootloader, use
// should_flash_in_userspace().
bool is_logical(const std::string& partition) {
std::string value;
return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
}
static uint64_t get_partition_size(const std::string& partition) {
std::string partition_size_str;
if (fb->GetVar("partition-size:" + partition, &partition_size_str) != fastboot::SUCCESS) {
if (!is_logical(partition)) {
return 0;
}
die("cannot get partition size for %s", partition.c_str());
}
partition_size_str = fb_fix_numeric_var(partition_size_str);
uint64_t partition_size;
if (!android::base::ParseUint(partition_size_str, &partition_size)) {
if (!is_logical(partition)) {
return 0;
}
die("Couldn't parse partition size '%s'.", partition_size_str.c_str());
}
return partition_size;
}
static void copy_avb_footer(const ImageSource* source, const std::string& partition,
struct fastboot_buffer* buf) {
if (buf->sz < AVB_FOOTER_SIZE || is_logical(partition) ||
should_flash_in_userspace(source, partition)) {
return;
}
// If the image is sparse, moving the footer will simply corrupt the sparse
// format, so currently we don't support moving the footer on sparse files.
if (buf->file_type == FB_BUFFER_SPARSE) {
LOG(ERROR) << "Warning: skip copying " << partition << " image avb footer due to sparse "
<< "image.";
return;
}
// If overflows and negative, it should be < buf->sz.
int64_t partition_size = static_cast<int64_t>(get_partition_size(partition));
if (partition_size == buf->sz) {
return;
}
// Some device bootloaders might not implement `fastboot getvar partition-size:boot[_a|_b]`.
// In this case, partition_size will be zero.
if (partition_size < buf->sz) {
fprintf(stderr,
"Warning: skip copying %s image avb footer"
" (%s partition size: %" PRId64 ", %s image size: %" PRId64 ").\n",
partition.c_str(), partition.c_str(), partition_size, partition.c_str(), buf->sz);
return;
}
// IMPORTANT: after the following read, we need to reset buf->fd before return (if not die).
// Because buf->fd will still be used afterwards.
std::string data;
if (!android::base::ReadFdToString(buf->fd, &data)) {
die("Failed reading from %s", partition.c_str());
}
uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
lseek(buf->fd.get(), 0, SEEK_SET); // IMPORTANT: resets buf->fd before return.
return;
}
const std::string tmp_fd_template = partition + " rewriting";
unique_fd fd(make_temporary_fd(tmp_fd_template.c_str()));
if (!android::base::WriteStringToFd(data, fd)) {
die("Failed writing to modified %s", partition.c_str());
}
lseek(fd.get(), partition_size - AVB_FOOTER_SIZE, SEEK_SET);
if (!android::base::WriteStringToFd(data.substr(footer_offset), fd)) {
die("Failed copying AVB footer in %s", partition.c_str());
}
buf->fd = std::move(fd);
buf->sz = partition_size;
lseek(buf->fd.get(), 0, SEEK_SET);
}
void flash_partition_files(const std::string& partition, const std::vector<SparsePtr>& files) {
for (size_t i = 0; i < files.size(); i++) {
sparse_file* s = files[i].get();
int64_t sz = sparse_file_len(s, true, false);
if (sz < 0) {
LOG(FATAL) << "Could not compute length of sparse image for " << partition;
}
fb->FlashPartition(partition, s, sz, i + 1, files.size());
}
}
static void flash_buf(const ImageSource* source, const std::string& partition,
struct fastboot_buffer* buf, const bool apply_vbmeta) {
copy_avb_footer(source, partition, buf);
// Rewrite vbmeta if that's what we're flashing and modification has been requested.
if (g_disable_verity || g_disable_verification) {
// The vbmeta partition might have additional prefix if running in virtual machine
// e.g., guest_vbmeta_a.
if (apply_vbmeta) {
rewrite_vbmeta_buffer(buf, false /* vbmeta_in_boot */);
} else if (!has_vbmeta_partition() &&
(partition == "boot" || partition == "boot_a" || partition == "boot_b")) {
rewrite_vbmeta_buffer(buf, true /* vbmeta_in_boot */);
}
}
switch (buf->type) {
case FB_BUFFER_SPARSE: {
flash_partition_files(partition, buf->files);
break;
}
case FB_BUFFER_FD:
fb->FlashPartition(partition, buf->fd, buf->sz);
break;
default:
die("unknown buffer type: %d", buf->type);
}
}
std::string get_current_slot() {
std::string current_slot;
if (fb->GetVar("current-slot", ¤t_slot) != fastboot::SUCCESS) return "";
if (current_slot[0] == '_') current_slot.erase(0, 1);
return current_slot;
}
static int get_slot_count(fastboot::IFastBootDriver* fb) {
std::string var;
int count = 0;
if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
!android::base::ParseInt(var, &count)) {
return 0;
}
return count;
}
bool supports_AB(fastboot::IFastBootDriver* fb) {
return get_slot_count(fb) >= 2;
}
// Given a current slot, this returns what the 'other' slot is.
static std::string get_other_slot(const std::string& current_slot, int count) {
if (count == 0) return "";
char next = (current_slot[0] - 'a' + 1) % count + 'a';
return std::string(1, next);
}
static std::string get_other_slot(const std::string& current_slot) {
return get_other_slot(current_slot, get_slot_count(fb));
}
static std::string get_other_slot(int count) {
return get_other_slot(get_current_slot(), count);
}
static std::string get_other_slot() {
return get_other_slot(get_current_slot(), get_slot_count(fb));
}
static std::string verify_slot(const std::string& slot_name, bool allow_all) {
std::string slot = slot_name;
if (slot == "all") {
if (allow_all) {
return "all";
} else {
int count = get_slot_count(fb);
if (count > 0) {
return "a";
} else {
die("No known slots");
}
}
}
int count = get_slot_count(fb);
if (count == 0) die("Device does not support slots");
if (slot == "other") {
std::string other = get_other_slot(count);
if (other == "") {
die("No known slots");
}
return other;
}
if (slot.size() == 1 && (slot[0] - 'a' >= 0 && slot[0] - 'a' < count)) return slot;
fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
for (int i = 0; i < count; i++) {
fprintf(stderr, "%c\n", (char)(i + 'a'));
}
exit(1);
}
static std::string verify_slot(const std::string& slot) {
return verify_slot(slot, true);
}
static void do_for_partition(const std::string& part, const std::string& slot,
const std::function<void(const std::string&)>& func, bool force_slot) {
std::string has_slot;
std::string current_slot;
// |part| can be vendor_boot:default. Append slot to the first token.
auto part_tokens = android::base::Split(part, ":");
if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
/* If has-slot is not supported, the answer is no. */
has_slot = "no";
}
if (has_slot == "yes") {
if (slot == "") {
current_slot = get_current_slot();
if (current_slot == "") {
die("Failed to identify current slot");
}
part_tokens[0] += "_" + current_slot;
} else {
part_tokens[0] += "_" + slot;
}
func(android::base::Join(part_tokens, ":"));
} else {
if (force_slot && slot != "") {
fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
part_tokens[0].c_str(), slot.c_str());
}
func(part);
}
}
/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
* empty, it will use the current slot. If slot is "all", it will return a list of all possible
* partition names. If force_slot is true, it will fail if a slot is specified, and the given
* partition does not support slots.
*/
void do_for_partitions(const std::string& part, const std::string& slot,
const std::function<void(const std::string&)>& func, bool force_slot) {
std::string has_slot;
// |part| can be vendor_boot:default. Query has-slot on the first token only.
auto part_tokens = android::base::Split(part, ":");
if (slot == "all") {
if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
die("Could not check if partition %s has slot %s", part_tokens[0].c_str(),
slot.c_str());
}
if (has_slot == "yes") {
for (int i = 0; i < get_slot_count(fb); i++) {
do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
}
} else {
do_for_partition(part, "", func, force_slot);
}
} else {
do_for_partition(part, slot, func, force_slot);
}
}
// Fetch a partition from the device to a given fd. This is a wrapper over FetchToFd to fetch
// the full image.
static uint64_t fetch_partition(const std::string& partition, borrowed_fd fd,
fastboot::IFastBootDriver* fb) {
uint64_t fetch_size = get_uint_var(FB_VAR_MAX_FETCH_SIZE, fb);
if (fetch_size == 0) {
die("Unable to get %s. Device does not support fetch command.", FB_VAR_MAX_FETCH_SIZE);
}
uint64_t partition_size = get_partition_size(partition);
if (partition_size <= 0) {
die("Invalid partition size for partition %s: %" PRId64, partition.c_str(), partition_size);
}
uint64_t offset = 0;
while (offset < partition_size) {
uint64_t chunk_size = std::min(fetch_size, partition_size - offset);
if (fb->FetchToFd(partition, fd, offset, chunk_size) != fastboot::RetCode::SUCCESS) {
die("Unable to fetch %s (offset=%" PRIx64 ", size=%" PRIx64 ")", partition.c_str(),
offset, chunk_size);
}
offset += chunk_size;
}
return partition_size;
}
static void do_fetch(const std::string& partition, const std::string& slot_override,
const std::string& outfile, fastboot::IFastBootDriver* fb) {
unique_fd fd(TEMP_FAILURE_RETRY(
open(outfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0644)));
auto fetch = std::bind(fetch_partition, _1, borrowed_fd(fd), fb);
do_for_partitions(partition, slot_override, fetch, false /* force slot */);
}
// Return immediately if not flashing a vendor boot image. If flashing a vendor boot image,
// repack vendor_boot image with an updated ramdisk. After execution, buf is set
// to the new image to flash, and return value is the real partition name to flash.
static std::string repack_ramdisk(const char* pname, struct fastboot_buffer* buf,
fastboot::IFastBootDriver* fb) {
std::string_view pname_sv{pname};
if (!android::base::StartsWith(pname_sv, "vendor_boot:") &&
!android::base::StartsWith(pname_sv, "vendor_boot_a:") &&
!android::base::StartsWith(pname_sv, "vendor_boot_b:")) {
return std::string(pname_sv);
}
if (buf->type != FB_BUFFER_FD) {
die("Flashing sparse vendor ramdisk image is not supported.");
}
if (buf->sz <= 0) {
die("repack_ramdisk() sees negative size: %" PRId64, buf->sz);
}
std::string partition(pname_sv.substr(0, pname_sv.find(':')));
std::string ramdisk(pname_sv.substr(pname_sv.find(':') + 1));
unique_fd vendor_boot(make_temporary_fd("vendor boot repack"));
uint64_t vendor_boot_size = fetch_partition(partition, vendor_boot, fb);
auto repack_res = replace_vendor_ramdisk(vendor_boot, vendor_boot_size, ramdisk, buf->fd,
static_cast<uint64_t>(buf->sz));
if (!repack_res.ok()) {
die("%s", repack_res.error().message().c_str());
}
buf->fd = std::move(vendor_boot);
buf->sz = vendor_boot_size;
buf->image_size = vendor_boot_size;
return partition;
}
void do_flash(const char* pname, const char* fname, const bool apply_vbmeta,
const FlashingPlan* fp) {
if (!fp) {
die("do flash was called without a valid flashing plan");
}
verbose("Do flash %s %s", pname, fname);
struct fastboot_buffer buf;
if (fp->source) {
unique_fd fd = fp->source->OpenFile(fname);
if (fd < 0 || !load_buf_fd(std::move(fd), &buf, fp)) {
die("could not load '%s': %s", fname, strerror(errno));
}
std::vector<char> signature_data;
std::string file_string(fname);
if (fp->source->ReadFile(file_string.substr(0, file_string.find('.')) + ".sig",
&signature_data)) {
fb->Download("signature", signature_data);
fb->RawCommand("signature", "installing signature");
}
} else if (!load_buf(fname, &buf, fp)) {
die("cannot load '%s': %s", fname, strerror(errno));
}
if (is_logical(pname)) {
fb->ResizePartition(pname, std::to_string(buf.image_size));
}
std::string flash_pname = repack_ramdisk(pname, &buf, fp->fb);
flash_buf(fp->source.get(), flash_pname, &buf, apply_vbmeta);
}
// Sets slot_override as the active slot. If slot_override is blank,
// set current slot as active instead. This clears slot-unbootable.
static void set_active(const std::string& slot_override) {
if (!supports_AB(fb)) return;
if (slot_override != "") {
fb->SetActive(slot_override);
} else {
std::string current_slot = get_current_slot();
if (current_slot != "") {
fb->SetActive(current_slot);
}
}
}
bool is_userspace_fastboot() {
std::string value;
return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
}
void reboot_to_userspace_fastboot() {
fb->RebootTo("fastboot");
if (fb->WaitForDisconnect() != fastboot::SUCCESS) {
die("Error waiting for USB disconnect.");
}
fb->set_transport(nullptr);
// Not all platforms support WaitForDisconnect. There also isn't a great way to tell whether
// or not WaitForDisconnect is supported. So, just wait a bit extra for everyone, in order to
// make sure that the device has had time to initiate its reboot and disconnect itself.
std::this_thread::sleep_for(std::chrono::seconds(1));
fb->set_transport(open_device());
if (!is_userspace_fastboot()) {
die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
}
// Reset target_sparse_limit after reboot to userspace fastboot. Max
// download sizes may differ in bootloader and fastbootd.
target_sparse_limit = -1;
}
static void CancelSnapshotIfNeeded() {
std::string merge_status = "none";
if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
!merge_status.empty() && merge_status != "none") {
fb->SnapshotUpdateCommand("cancel");
}
}
std::string GetPartitionName(const ImageEntry& entry, const std::string& current_slot) {
auto slot = entry.second;
if (slot.empty()) {
slot = current_slot;
}
if (slot.empty()) {
return entry.first->part_name;
}
if (slot == "all") {
LOG(FATAL) << "Cannot retrieve a singular name when using all slots";
}
return entry.first->part_name + "_" + slot;
}
std::unique_ptr<FlashTask> ParseFlashCommand(const FlashingPlan* fp,
const std::vector<std::string>& parts) {
bool apply_vbmeta = false;
std::string slot = fp->slot_override;
std::string partition;
std::string img_name;
for (auto& part : parts) {
if (part == "--apply-vbmeta") {
apply_vbmeta = true;
} else if (part == "--slot-other") {
slot = fp->secondary_slot;
} else if (partition.empty()) {
partition = part;
} else if (img_name.empty()) {
img_name = part;
} else {
LOG(ERROR) << "unknown argument" << part
<< " in fastboot-info.txt. parts: " << android::base::Join(parts, " ");
return nullptr;
}
}
if (partition.empty()) {
LOG(ERROR) << "partition name not found when parsing fastboot-info.txt. parts: "
<< android::base::Join(parts, " ");
return nullptr;
}
if (img_name.empty()) {
img_name = partition + ".img";
}
return std::make_unique<FlashTask>(slot, partition, img_name, apply_vbmeta, fp);
}
std::unique_ptr<RebootTask> ParseRebootCommand(const FlashingPlan* fp,
const std::vector<std::string>& parts) {
if (parts.empty()) return std::make_unique<RebootTask>(fp);
if (parts.size() > 1) {
LOG(ERROR) << "unknown arguments in reboot {target} in fastboot-info.txt: "
<< android::base::Join(parts, " ");
return nullptr;
}
return std::make_unique<RebootTask>(fp, parts[0]);
}
std::unique_ptr<WipeTask> ParseWipeCommand(const FlashingPlan* fp,
const std::vector<std::string>& parts) {
if (parts.size() != 1) {
LOG(ERROR) << "unknown arguments in erase {partition} in fastboot-info.txt: "
<< android::base::Join(parts, " ");
return nullptr;
}
return std::make_unique<WipeTask>(fp, parts[0]);
}
std::unique_ptr<Task> ParseFastbootInfoLine(const FlashingPlan* fp,
const std::vector<std::string>& command) {
if (command.size() == 0) {
return nullptr;
}
std::unique_ptr<Task> task;
if (command[0] == "flash") {
task = ParseFlashCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
} else if (command[0] == "reboot") {
task = ParseRebootCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
} else if (command[0] == "update-super" && command.size() == 1) {
task = std::make_unique<UpdateSuperTask>(fp);
} else if (command[0] == "erase" && command.size() == 2) {
task = ParseWipeCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
}
if (!task) {
LOG(ERROR) << "unknown command parsing fastboot-info.txt line: "
<< android::base::Join(command, " ");
}
return task;
}
bool AddResizeTasks(const FlashingPlan* fp, std::vector<std::unique_ptr<Task>>* tasks) {
// expands "resize-partitions" into individual commands : resize {os_partition_1}, resize
// {os_partition_2}, etc.
std::vector<std::unique_ptr<Task>> resize_tasks;
std::optional<size_t> loc;
std::vector<char> contents;
if (!fp->source->ReadFile("super_empty.img", &contents)) {
return false;
}
auto metadata = android::fs_mgr::ReadFromImageBlob(contents.data(), contents.size());
if (!metadata) {
return false;
}
for (size_t i = 0; i < tasks->size(); i++) {
if (auto flash_task = tasks->at(i)->AsFlashTask()) {
if (FlashTask::IsDynamicPartition(fp->source.get(), flash_task)) {
if (!loc) {
loc = i;
}
resize_tasks.emplace_back(std::make_unique<ResizeTask>(
fp, flash_task->GetPartition(), "0", fp->slot_override));
}
}
}
// if no logical partitions (although should never happen since system will always need to be
// flashed)
if (!loc) {
return false;
}
tasks->insert(tasks->begin() + loc.value(), std::make_move_iterator(resize_tasks.begin()),
std::make_move_iterator(resize_tasks.end()));
return true;
}
static bool IsIgnore(const std::vector<std::string>& command) {
if (command.size() == 0 || command[0][0] == '#') {
return true;
}
return false;
}
bool CheckFastbootInfoRequirements(const std::vector<std::string>& command,
uint32_t host_tool_version) {
if (command.size() != 2) {
LOG(ERROR) << "unknown characters in version info in fastboot-info.txt -> "
<< android::base::Join(command, " ");
return false;
}
if (command[0] != "version") {
LOG(ERROR) << "unknown characters in version info in fastboot-info.txt -> "
<< android::base::Join(command, " ");
return false;
}
uint32_t fastboot_info_version;
if (!android::base::ParseUint(command[1], &fastboot_info_version)) {
LOG(ERROR) << "version number contains non-numeric characters in fastboot-info.txt -> "
<< android::base::Join(command, " ");
return false;
}
LOG(VERBOSE) << "Checking 'fastboot-info.txt version'";
if (fastboot_info_version <= host_tool_version) {
return true;
}
LOG(ERROR) << "fasboot-info.txt version: " << command[1]
<< " not compatible with host tool version --> " << host_tool_version;
return false;
}
std::vector<std::unique_ptr<Task>> ParseFastbootInfo(const FlashingPlan* fp,
const std::vector<std::string>& file) {
std::vector<std::unique_ptr<Task>> tasks;
// Get os_partitions that need to be resized
for (auto& text : file) {
std::vector<std::string> command = android::base::Tokenize(text, " ");
if (IsIgnore(command)) {
continue;
}
if (command.size() > 1 && command[0] == "version") {
if (!CheckFastbootInfoRequirements(command, FASTBOOT_INFO_VERSION)) {
return {};
}
continue;
} else if (command.size() >= 2 && command[0] == "if-wipe") {
if (!fp->wants_wipe) {
continue;
}
command.erase(command.begin());
}
auto task = ParseFastbootInfoLine(fp, command);
if (!task) {
return {};
}
tasks.emplace_back(std::move(task));
}
if (auto flash_super_task = OptimizedFlashSuperTask::Initialize(fp, tasks)) {
tasks.emplace_back(std::move(flash_super_task));
} else {
if (!AddResizeTasks(fp, &tasks)) {
LOG(WARNING) << "Failed to add resize tasks";
}
}
return tasks;
}
FlashAllTool::FlashAllTool(FlashingPlan* fp) : fp_(fp) {}
void FlashAllTool::Flash() {
DumpInfo();
CheckRequirements();
// Change the slot first, so we boot into the correct recovery image when
// using fastbootd.
if (fp_->slot_override == "all") {
set_active("a");
} else {
set_active(fp_->slot_override);
}
DetermineSlot();
CancelSnapshotIfNeeded();
tasks_ = CollectTasks();
for (auto& task : tasks_) {
task->Run();
}
return;
}
std::vector<std::unique_ptr<Task>> FlashAllTool::CollectTasks() {
std::vector<std::unique_ptr<Task>> tasks;
if (fp_->should_use_fastboot_info) {
tasks = CollectTasksFromFastbootInfo();
} else {
tasks = CollectTasksFromImageList();
}
if (fp_->exclude_dynamic_partitions) {
auto is_non_static_flash_task = [&](const auto& task) -> bool {
if (auto flash_task = task->AsFlashTask()) {
if (!should_flash_in_userspace(fp_->source.get(),
flash_task->GetPartitionAndSlot())) {
return false;
}
}
return true;
};
tasks.erase(std::remove_if(tasks.begin(), tasks.end(), is_non_static_flash_task),
tasks.end());
}
return tasks;
}
void FlashAllTool::CheckRequirements() {
std::vector<char> contents;
if (!fp_->source->ReadFile("android-info.txt", &contents)) {
die("could not read android-info.txt");
}
::CheckRequirements({contents.data(), contents.size()}, fp_->force_flash);
}
void FlashAllTool::DetermineSlot() {
if (fp_->slot_override.empty()) {
fp_->current_slot = get_current_slot();
} else {
fp_->current_slot = fp_->slot_override;
}
if (fp_->skip_secondary) {
return;
}
if (fp_->slot_override != "" && fp_->slot_override != "all") {
fp_->secondary_slot = get_other_slot(fp_->slot_override);
} else {
fp_->secondary_slot = get_other_slot();
}
if (fp_->secondary_slot == "") {
if (supports_AB(fb)) {
fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
}
fp_->skip_secondary = true;
}
}
void FlashAllTool::CollectImages() {
for (size_t i = 0; i < images.size(); ++i) {
std::string slot = fp_->slot_override;
if (images[i].IsSecondary()) {
if (fp_->skip_secondary) {
continue;
}
slot = fp_->secondary_slot;
}
if (images[i].type == ImageType::BootCritical) {
boot_images_.emplace_back(&images[i], slot);
} else if (images[i].type == ImageType::Normal) {
os_images_.emplace_back(&images[i], slot);
}
}
}
std::vector<std::unique_ptr<Task>> FlashAllTool::CollectTasksFromImageList() {
CollectImages();
// First flash boot partitions. We allow this to happen either in userspace
// or in bootloader fastboot.
std::vector<std::unique_ptr<Task>> tasks;
AddFlashTasks(boot_images_, tasks);
// Sync the super partition. This will reboot to userspace fastboot if needed.
tasks.emplace_back(std::make_unique<UpdateSuperTask>(fp_));
AddFlashTasks(os_images_, tasks);
if (auto flash_super_task = OptimizedFlashSuperTask::Initialize(fp_, tasks)) {
tasks.emplace_back(std::move(flash_super_task));
} else {
// Resize any logical partition to 0, so each partition is reset to 0
// extents, and will achieve more optimal allocation.
if (!AddResizeTasks(fp_, &tasks)) {
LOG(WARNING) << "Failed to add resize tasks";
}
}
return tasks;
}
std::vector<std::unique_ptr<Task>> FlashAllTool::CollectTasksFromFastbootInfo() {
std::vector<std::unique_ptr<Task>> tasks;
std::vector<char> contents;
if (!fp_->source->ReadFile("fastboot-info.txt", &contents)) {
LOG(VERBOSE) << "Flashing from hardcoded images. fastboot-info.txt is empty or does not "
"exist";
return CollectTasksFromImageList();
}
tasks = ParseFastbootInfo(fp_, Split({contents.data(), contents.size()}, "\n"));
return tasks;
}
void FlashAllTool::AddFlashTasks(const std::vector<std::pair<const Image*, std::string>>& images,
std::vector<std::unique_ptr<Task>>& tasks) {
for (const auto& [image, slot] : images) {
fastboot_buffer buf;
unique_fd fd = fp_->source->OpenFile(image->img_name);
if (fd < 0 || !load_buf_fd(std::move(fd), &buf, fp_)) {
if (image->optional_if_no_image) {
continue;
}
die("could not load '%s': %s", image->img_name.c_str(), strerror(errno));
}
tasks.emplace_back(std::make_unique<FlashTask>(slot, image->part_name, image->img_name,
is_vbmeta_partition(image->part_name), fp_));
}
}
bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
return UnzipToMemory(zip_, name, out);
}
unique_fd ZipImageSource::OpenFile(const std::string& name) const {
return UnzipToFile(zip_, name.c_str());
}
static void do_update(const char* filename, FlashingPlan* fp) {
ZipArchiveHandle zip;
int error = OpenArchive(filename, &zip);
if (error != 0) {
die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
}
fp->source.reset(new ZipImageSource(zip));
FlashAllTool tool(fp);
tool.Flash();
CloseArchive(zip);
}
bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
auto path = find_item_given_name(name);
if (path.empty()) {
return false;
}
return ReadFileToVector(path, out);
}
unique_fd LocalImageSource::OpenFile(const std::string& name) const {
auto path = find_item_given_name(name);
return unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_BINARY)));
}
static void do_flashall(FlashingPlan* fp) {
fp->source.reset(new LocalImageSource());
FlashAllTool tool(fp);
tool.Flash();
}
static std::string next_arg(std::vector<std::string>* args) {
if (args->empty()) syntax_error("expected argument");
std::string result = args->front();
args->erase(args->begin());
return result;
}
static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
if (args->empty()) syntax_error("empty oem command");
std::string command(cmd);
while (!args->empty()) {
command += " " + next_arg(args);
}
fb->RawCommand(command, "");
}
static unsigned fb_get_flash_block_size(std::string name) {
std::string sizeString;
if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
// This device does not report flash block sizes, so return 0.
return 0;
}
sizeString = fb_fix_numeric_var(sizeString);
unsigned size;
if (!android::base::ParseUint(sizeString, &size)) {
fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
return 0;
}
if ((size & (size - 1)) != 0) {
fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
return 0;
}
return size;
}
void fb_perform_format(const std::string& partition, int skip_if_not_supported,
const std::string& type_override, const std::string& size_override,
const unsigned fs_options, const FlashingPlan* fp) {
std::string partition_type, partition_size;
struct fastboot_buffer buf;
const char* errMsg = nullptr;
const struct fs_generator* gen = nullptr;
TemporaryFile output;
unique_fd fd;
unsigned int limit = INT_MAX;
if (target_sparse_limit > 0 && target_sparse_limit < limit) {
limit = target_sparse_limit;
}
if (fp->sparse_limit > 0 && fp->sparse_limit < limit) {
limit = fp->sparse_limit;
}
if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
errMsg = "Can't determine partition type.\n";
goto failed;
}
if (!type_override.empty()) {
if (partition_type != type_override) {
fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
partition.c_str(), partition_type.c_str(), type_override.c_str());
}
partition_type = type_override;
}
if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
errMsg = "Unable to get partition size\n";
goto failed;
}
if (!size_override.empty()) {
if (partition_size != size_override) {
fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
partition.c_str(), partition_size.c_str(), size_override.c_str());
}
partition_size = size_override;
}
partition_size = fb_fix_numeric_var(partition_size);
gen = fs_get_generator(partition_type);
if (!gen) {
if (skip_if_not_supported) {
fprintf(stderr, "Erase successful, but not automatically formatting.\n");
fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
return;
}
die("Formatting is not supported for file system with type '%s'.", partition_type.c_str());
}
int64_t size;
if (!android::base::ParseInt(partition_size, &size)) {
die("Couldn't parse partition size '%s'.", partition_size.c_str());
}
unsigned eraseBlkSize, logicalBlkSize;
eraseBlkSize = fb_get_flash_block_size("erase-block-size");
logicalBlkSize = fb_get_flash_block_size("logical-block-size");
if (fs_generator_generate(gen, output.path, size, eraseBlkSize, logicalBlkSize, fs_options)) {
die("Cannot generate image for %s", partition.c_str());
}
fd.reset(open(output.path, O_RDONLY));
if (fd == -1) {
die("Cannot open generated image: %s", strerror(errno));
}
if (!load_buf_fd(std::move(fd), &buf, fp)) {
die("Cannot read image: %s", strerror(errno));
}
flash_buf(fp->source.get(), partition, &buf, is_vbmeta_partition(partition));
return;
failed:
if (skip_if_not_supported) {
fprintf(stderr, "Erase successful, but not automatically formatting.\n");
if (errMsg) fprintf(stderr, "%s", errMsg);
}
fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
if (!skip_if_not_supported) {
die("Command failed");
}
}
bool should_flash_in_userspace(const ImageSource* source, const std::string& partition_name) {
if (!source) {
if (!get_android_product_out()) {
return false;
}
auto path = find_item_given_name("super_empty.img");
if (path.empty() || access(path.c_str(), R_OK)) {
return false;
}
auto metadata = android::fs_mgr::ReadFromImageFile(path);
if (!metadata) {
return false;
}
return should_flash_in_userspace(*metadata.get(), partition_name);
}
std::vector<char> contents;
if (!source->ReadFile("super_empty.img", &contents)) {
return false;
}
auto metadata = android::fs_mgr::ReadFromImageBlob(contents.data(), contents.size());
return should_flash_in_userspace(*metadata.get(), partition_name);
}
static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
std::string* message, const FlashingPlan* fp) {
auto super_device = GetMetadataSuperBlockDevice(metadata);
auto block_size = metadata.geometry.logical_block_size;
auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
if (super_bdev_name != "super") {
// retrofit devices do not allow flashing to the retrofit partitions,
// so enable it if we can.
fb->RawCommand("oem allow-flash-super");
}
// Note: do not use die() in here, since we want TemporaryDir's destructor
// to be called.
TemporaryDir temp_dir;
bool ok;
if (metadata.block_devices.size() > 1) {
ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
} else {
auto image_path = std::string(temp_dir.path) + "/" + std::string(super_bdev_name) + ".img";
ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
}
if (!ok) {
*message = "Could not generate a flashable super image file";
return false;
}
for (const auto& block_device : metadata.block_devices) {
auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
std::string image_name;
if (metadata.block_devices.size() > 1) {
image_name = "super_" + partition + ".img";
} else {
image_name = partition + ".img";
}
auto image_path = std::string(temp_dir.path) + "/" + image_name;
auto flash = [&](const std::string& partition_name) {
do_flash(partition_name.c_str(), image_path.c_str(), false, fp);
};
do_for_partitions(partition, slot, flash, force_slot);
unlink(image_path.c_str());
}
return true;
}
static void do_wipe_super(const std::string& image, const std::string& slot_override,
const FlashingPlan* fp) {
if (access(image.c_str(), R_OK) != 0) {
die("Could not read image: %s", image.c_str());
}
auto metadata = android::fs_mgr::ReadFromImageFile(image);
if (!metadata) {
die("Could not parse image: %s", image.c_str());
}
auto slot = slot_override;
if (slot.empty()) {
slot = get_current_slot();
}
std::string message;
if (!wipe_super(*metadata.get(), slot, &message, fp)) {
die(message);
}
}
static void FastbootLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
const char* /* tag */, const char* /* file */, unsigned int /* line */,
const char* message) {
switch (severity) {
case android::base::INFO:
fprintf(stdout, "%s\n", message);
break;
case android::base::ERROR:
fprintf(stderr, "%s\n", message);
break;
default:
verbose("%s\n", message);
}
}
static void FastbootAborter(const char* message) {
die("%s", message);
}
int FastBootTool::Main(int argc, char* argv[]) {
android::base::InitLogging(argv, FastbootLogger, FastbootAborter);
std::unique_ptr<FlashingPlan> fp = std::make_unique<FlashingPlan>();
int longindex;
std::string next_active;
g_boot_img_hdr.kernel_addr = 0x00008000;
g_boot_img_hdr.ramdisk_addr = 0x01000000;
g_boot_img_hdr.second_addr = 0x00f00000;
g_boot_img_hdr.tags_addr = 0x00000100;
g_boot_img_hdr.page_size = 2048;
g_boot_img_hdr.dtb_addr = 0x01100000;
const struct option longopts[] = {{"base", required_argument, 0, 0},
{"cmdline", required_argument, 0, 0},
{"disable-verification", no_argument, 0, 0},
{"disable-verity", no_argument, 0, 0},
{"disable-super-optimization", no_argument, 0, 0},
{"exclude-dynamic-partitions", no_argument, 0, 0},
{"disable-fastboot-info", no_argument, 0, 0},
{"force", no_argument, 0, 0},
{"fs-options", required_argument, 0, 0},
{"header-version", required_argument, 0, 0},
{"help", no_argument, 0, 'h'},
{"kernel-offset", required_argument, 0, 0},
{"os-patch-level", required_argument, 0, 0},
{"os-version", required_argument, 0, 0},
{"page-size", required_argument, 0, 0},
{"ramdisk-offset", required_argument, 0, 0},
{"set-active", optional_argument, 0, 'a'},
{"skip-reboot", no_argument, 0, 0},
{"skip-secondary", no_argument, 0, 0},
{"slot", required_argument, 0, 0},
{"tags-offset", required_argument, 0, 0},
{"dtb", required_argument, 0, 0},
{"dtb-offset", required_argument, 0, 0},
{"unbuffered", no_argument, 0, 0},
{"verbose", no_argument, 0, 'v'},
{"version", no_argument, 0, 0},
{0, 0, 0, 0}};
serial = getenv("FASTBOOT_DEVICE");
if (!serial) {
serial = getenv("ANDROID_SERIAL");
}
int c;
while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
if (c == 0) {
std::string name{longopts[longindex].name};
if (name == "base") {
g_base_addr = strtoul(optarg, 0, 16);
} else if (name == "cmdline") {
g_cmdline = optarg;
} else if (name == "disable-verification") {
g_disable_verification = true;
} else if (name == "disable-verity") {
g_disable_verity = true;
} else if (name == "disable-super-optimization") {
fp->should_optimize_flash_super = false;
} else if (name == "exclude-dynamic-partitions") {
fp->exclude_dynamic_partitions = true;
fp->should_optimize_flash_super = false;
} else if (name == "disable-fastboot-info") {
fp->should_use_fastboot_info = false;
} else if (name == "force") {
fp->force_flash = true;
} else if (name == "fs-options") {
fp->fs_options = ParseFsOption(optarg);
} else if (name == "header-version") {
g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
} else if (name == "dtb") {
g_dtb_path = optarg;
} else if (name == "kernel-offset") {
g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
} else if (name == "os-patch-level") {
ParseOsPatchLevel(&g_boot_img_hdr, optarg);
} else if (name == "os-version") {
ParseOsVersion(&g_boot_img_hdr, optarg);
} else if (name == "page-size") {
g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
if (g_boot_img_hdr.page_size == 0) die("invalid page size");
} else if (name == "ramdisk-offset") {
g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
} else if (name == "skip-reboot") {
fp->skip_reboot = true;
} else if (name == "skip-secondary") {
fp->skip_secondary = true;
} else if (name == "slot") {
fp->slot_override = optarg;
} else if (name == "dtb-offset") {
g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
} else if (name == "tags-offset") {
g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
} else if (name == "unbuffered") {
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
} else if (name == "version") {
fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION, "debian");
fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
return 0;
} else {
die("unknown option %s", longopts[longindex].name);
}
} else {
switch (c) {
case 'a':
fp->wants_set_active = true;
if (optarg) next_active = optarg;
break;
case 'h':
return show_help();
case 'l':
g_long_listing = true;
break;
case 's':
serial = optarg;
break;
case 'S':
if (!android::base::ParseByteCount(optarg, &fp->sparse_limit)) {
die("invalid sparse limit %s", optarg);
}
break;
case 'v':
set_verbose();
break;
case 'w':
fp->wants_wipe = true;
break;
case '?':
return 1;
default:
abort();
}
}
}
argc -= optind;
argv += optind;
if (argc == 0 && !fp->wants_wipe && !fp->wants_set_active) syntax_error("no command");
if (argc > 0 && !strcmp(*argv, "devices")) {
list_devices();
return 0;
}
if (argc > 0 && !strcmp(*argv, "connect")) {
argc -= optind;
argv += optind;
return Connect(argc, argv);
}
if (argc > 0 && !strcmp(*argv, "disconnect")) {
argc -= optind;
argv += optind;
return Disconnect(argc, argv);
}
if (argc > 0 && !strcmp(*argv, "help")) {
return show_help();
}
std::unique_ptr<Transport> transport = open_device();
if (!transport) {
return 1;
}
fastboot::DriverCallbacks driver_callbacks = {
.prolog = Status,
.epilog = Epilog,
.info = InfoMessage,
.text = TextMessage,
};
fastboot::FastBootDriver fastboot_driver(std::move(transport), driver_callbacks, false);
fb = &fastboot_driver;
fp->fb = &fastboot_driver;
const double start = now();
if (fp->slot_override != "") fp->slot_override = verify_slot(fp->slot_override);
if (next_active != "") next_active = verify_slot(next_active, false);
if (fp->wants_set_active) {
if (next_active == "") {
if (fp->slot_override == "") {
std::string current_slot;
if (fb->GetVar("current-slot", ¤t_slot) == fastboot::SUCCESS) {
if (current_slot[0] == '_') current_slot.erase(0, 1);
next_active = verify_slot(current_slot, false);
} else {
fp->wants_set_active = false;
}
} else {
next_active = verify_slot(fp->slot_override, false);
}
}
}
std::vector<std::unique_ptr<Task>> tasks;
std::vector<std::string> args(argv, argv + argc);
while (!args.empty()) {
std::string command = next_arg(&args);
if (command == FB_CMD_GETVAR) {
std::string variable = next_arg(&args);
DisplayVarOrError(variable, variable);
} else if (command == FB_CMD_ERASE) {
std::string partition = next_arg(&args);
auto erase = [&](const std::string& partition) {
std::string partition_type;
if (fb->GetVar("partition-type:" + partition, &partition_type) ==
fastboot::SUCCESS &&
fs_get_generator(partition_type) != nullptr) {
fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
partition_type.c_str());
}
fb->Erase(partition);
};
do_for_partitions(partition, fp->slot_override, erase, true);
} else if (android::base::StartsWith(command, "format")) {
// Parsing for: "format[:[type][:[size]]]"
// Some valid things:
// - select only the size, and leave default fs type:
// format::0x4000000 userdata
// - default fs type and size:
// format userdata
// format:: userdata
std::vector<std::string> pieces = android::base::Split(command, ":");
std::string type_override;
if (pieces.size() > 1) type_override = pieces[1].c_str();
std::string size_override;
if (pieces.size() > 2) size_override = pieces[2].c_str();
std::string partition = next_arg(&args);
auto format = [&](const std::string& partition) {
fb_perform_format(partition, 0, type_override, size_override, fp->fs_options,
fp.get());
};
do_for_partitions(partition, fp->slot_override, format, true);
} else if (command == "signature") {
std::string filename = next_arg(&args);
std::vector<char> data;
if (!ReadFileToVector(filename, &data)) {
die("could not load '%s': %s", filename.c_str(), strerror(errno));
}
if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
fb->Download("signature", data);
fb->RawCommand("signature", "installing signature");
} else if (command == FB_CMD_REBOOT) {
if (args.size() == 1) {
std::string reboot_target = next_arg(&args);
tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), reboot_target));
} else if (!fp->skip_reboot) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
}
if (!args.empty()) syntax_error("junk after reboot command");
} else if (command == FB_CMD_REBOOT_BOOTLOADER) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "bootloader"));
} else if (command == FB_CMD_REBOOT_RECOVERY) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "recovery"));
} else if (command == FB_CMD_REBOOT_FASTBOOT) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "fastboot"));
} else if (command == FB_CMD_CONTINUE) {
fb->Continue();
} else if (command == FB_CMD_BOOT) {
std::string kernel = next_arg(&args);
std::string ramdisk;
if (!args.empty()) ramdisk = next_arg(&args);
std::string second_stage;
if (!args.empty()) second_stage = next_arg(&args);
auto data = LoadBootableImage(kernel, ramdisk, second_stage);
fb->Download("boot.img", data);
fb->Boot();
} else if (command == FB_CMD_FLASH) {
std::string pname = next_arg(&args);
std::string fname;
if (!args.empty()) {
fname = next_arg(&args);
} else {
fname = find_item(pname);
}
if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
FlashTask task(fp->slot_override, pname, fname, is_vbmeta_partition(pname), fp.get());
task.Run();
} else if (command == "flash:raw") {
std::string partition = next_arg(&args);
std::string kernel = next_arg(&args);
std::string ramdisk;
if (!args.empty()) ramdisk = next_arg(&args);
std::string second_stage;
if (!args.empty()) second_stage = next_arg(&args);
auto data = LoadBootableImage(kernel, ramdisk, second_stage);
auto flashraw = [&data](const std::string& partition) {
fb->FlashPartition(partition, data);
};
do_for_partitions(partition, fp->slot_override, flashraw, true);
} else if (command == "flashall") {
if (fp->slot_override == "all") {
fprintf(stderr,
"Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
fp->skip_secondary = true;
}
do_flashall(fp.get());
if (!fp->skip_reboot) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
}
} else if (command == "update") {
bool slot_all = (fp->slot_override == "all");
if (slot_all) {
fprintf(stderr,
"Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
}
std::string filename = "update.zip";
if (!args.empty()) {
filename = next_arg(&args);
}
do_update(filename.c_str(), fp.get());
if (!fp->skip_reboot) {
tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
}
} else if (command == FB_CMD_SET_ACTIVE) {
std::string slot = verify_slot(next_arg(&args), false);
fb->SetActive(slot);
} else if (command == "stage") {
std::string filename = next_arg(&args);
struct fastboot_buffer buf;
if (!load_buf(filename.c_str(), &buf, fp.get()) || buf.type != FB_BUFFER_FD) {
die("cannot load '%s'", filename.c_str());
}
fb->Download(filename, buf.fd.get(), buf.sz);
} else if (command == "get_staged") {
std::string filename = next_arg(&args);
fb->Upload(filename);
} else if (command == FB_CMD_OEM) {
do_oem_command(FB_CMD_OEM, &args);
} else if (command == "flashing") {
if (args.empty()) {
syntax_error("missing 'flashing' command");
} else if (args.size() == 1 &&
(args[0] == "unlock" || args[0] == "lock" || args[0] == "unlock_critical" ||
args[0] == "lock_critical" || args[0] == "get_unlock_ability")) {
do_oem_command("flashing", &args);
} else {
syntax_error("unknown 'flashing' command %s", args[0].c_str());
}
} else if (command == FB_CMD_CREATE_PARTITION) {
std::string partition = next_arg(&args);
std::string size = next_arg(&args);
fb->CreatePartition(partition, size);
} else if (command == FB_CMD_DELETE_PARTITION) {
std::string partition = next_arg(&args);
tasks.emplace_back(std::make_unique<DeleteTask>(fp.get(), partition));
} else if (command == FB_CMD_RESIZE_PARTITION) {
std::string partition = next_arg(&args);
std::string size = next_arg(&args);
std::unique_ptr<ResizeTask> resize_task =
std::make_unique<ResizeTask>(fp.get(), partition, size, fp->slot_override);
resize_task->Run();
} else if (command == "gsi") {
if (args.empty()) syntax_error("invalid gsi command");
std::string cmd("gsi");
while (!args.empty()) {
cmd += ":" + next_arg(&args);
}
fb->RawCommand(cmd, "");
} else if (command == "wipe-super") {
std::string image;
if (args.empty()) {
image = find_item_given_name("super_empty.img");
} else {
image = next_arg(&args);
}
do_wipe_super(image, fp->slot_override, fp.get());
} else if (command == "snapshot-update") {
std::string arg;
if (!args.empty()) {
arg = next_arg(&args);
}
if (!arg.empty() && (arg != "cancel" && arg != "merge")) {
syntax_error("expected: snapshot-update [cancel|merge]");
}
fb->SnapshotUpdateCommand(arg);
} else if (command == FB_CMD_FETCH) {
std::string partition = next_arg(&args);
std::string outfile = next_arg(&args);
do_fetch(partition, fp->slot_override, outfile, fp->fb);
} else {
syntax_error("unknown command %s", command.c_str());
}
}
if (fp->wants_wipe) {
if (fp->force_flash) {
CancelSnapshotIfNeeded();
}
std::vector<std::unique_ptr<Task>> wipe_tasks;
std::vector<std::string> partitions = {"userdata", "cache", "metadata"};
for (const auto& partition : partitions) {
wipe_tasks.emplace_back(std::make_unique<WipeTask>(fp.get(), partition));
}
tasks.insert(tasks.begin(), std::make_move_iterator(wipe_tasks.begin()),
std::make_move_iterator(wipe_tasks.end()));
}
if (fp->wants_set_active) {
fb->SetActive(next_active);
}
for (auto& task : tasks) {
task->Run();
}
fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
return 0;
}
void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
unsigned year, month, day;
if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
}
if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
hdr->SetOsPatchLevel(year, month);
}
void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
unsigned major = 0, minor = 0, patch = 0;
std::vector<std::string> versions = android::base::Split(arg, ".");
if (versions.size() < 1 || versions.size() > 3 ||
(versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
(versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
(versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
(major > 0x7f || minor > 0x7f || patch > 0x7f)) {
syntax_error("bad OS version: %s", arg);
}
hdr->SetOsVersion(major, minor, patch);
}
unsigned FastBootTool::ParseFsOption(const char* arg) {
unsigned fsOptions = 0;
std::vector<std::string> options = android::base::Split(arg, ",");
if (options.size() < 1) syntax_error("bad options: %s", arg);
for (size_t i = 0; i < options.size(); ++i) {
if (options[i] == "casefold")
fsOptions |= (1 << FS_OPT_CASEFOLD);
else if (options[i] == "projid")
fsOptions |= (1 << FS_OPT_PROJID);
else if (options[i] == "compress")
fsOptions |= (1 << FS_OPT_COMPRESS);
else
syntax_error("unsupported options: %s", options[i].c_str());
}
return fsOptions;
}
|