blob: e5319a5aa9d658458cb4760f71b0b738307cb540 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
Tsu Chiang Chuangee520552011-02-25 18:38:53 -080012 * the documentation and/or other materials provided with the
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080013 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
Tsu Chiang Chuangee520552011-02-25 18:38:53 -080022 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Tom Cherry9027af02018-09-24 15:48:09 -070029#include "fastboot.h"
30
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070031#include <ctype.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032#include <errno.h>
33#include <fcntl.h>
Colin Cross8879f982012-05-22 17:53:34 -070034#include <getopt.h>
Ying Wangcf86e2f2014-05-15 20:06:40 -070035#include <inttypes.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070036#include <limits.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070037#include <stdint.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <sys/stat.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#include <sys/time.h>
Colin Crossf8387882012-05-24 17:18:41 -070043#include <sys/types.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070044#include <unistd.h>
David Pursell2ec418a2016-01-20 08:32:08 -080045
Elliott Hughes290a2282016-11-14 17:08:47 -080046#include <chrono>
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -070047#include <functional>
Tom Cherry4aa60b32018-09-05 15:11:44 -070048#include <regex>
David Anderson0c732342018-11-28 17:10:42 -080049#include <string>
Elliott Hughes290a2282016-11-14 17:08:47 -080050#include <thread>
Josh Gao9da9ac52016-01-19 14:50:18 -080051#include <utility>
52#include <vector>
Colin Crossf8387882012-05-24 17:18:41 -070053
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080054#include <android-base/endian.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070055#include <android-base/file.h>
Elliott Hughes749ae2d2016-06-28 14:48:45 -070056#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080057#include <android-base/parseint.h>
David Pursell2ec418a2016-01-20 08:32:08 -080058#include <android-base/parsenetaddress.h>
Elliott Hughes2810d002016-04-25 14:31:18 -070059#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080060#include <android-base/strings.h>
Chris Fries0ea946c2017-04-12 10:25:57 -050061#include <android-base/unique_fd.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070062#include <build/version.h>
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080063#include <libavb/libavb.h>
David Anderson89569642018-11-16 15:53:35 -080064#include <liblp/liblp.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070065#include <platform_tools_version.h>
Colin Crossf8387882012-05-24 17:18:41 -070066#include <sparse/sparse.h>
Elliott Hughesd30ad8a2015-03-18 23:12:44 -070067#include <ziparchive/zip_archive.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080068
Elliott Hughes253c18d2015-03-18 22:47:09 -070069#include "bootimg_utils.h"
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -070070#include "constants.h"
Elliott Hughes1b708d32015-12-11 19:07:01 -080071#include "diagnose_usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070072#include "fastboot_driver.h"
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -070073#include "fs.h"
David Pursell2ec418a2016-01-20 08:32:08 -080074#include "tcp.h"
David Pursell0b156632015-10-30 11:22:01 -070075#include "transport.h"
David Pursell4601c972016-02-05 15:35:09 -080076#include "udp.h"
David Pursell0b156632015-10-30 11:22:01 -070077#include "usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070078#include "util.h"
Yifan Honge71fe242021-02-22 15:00:15 -080079#include "vendor_boot_img_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080080
Yifan Hongbcd27702021-02-16 19:37:32 -080081using android::base::borrowed_fd;
Tom Cherrydfd85df2018-09-20 14:45:05 -070082using android::base::ReadFully;
Tom Cherry4aa60b32018-09-05 15:11:44 -070083using android::base::Split;
84using android::base::Trim;
Chris Fries0ea946c2017-04-12 10:25:57 -050085using android::base::unique_fd;
David Anderson0c732342018-11-28 17:10:42 -080086using namespace std::string_literals;
Yifan Hongbcd27702021-02-16 19:37:32 -080087using namespace std::placeholders;
Chris Fries0ea946c2017-04-12 10:25:57 -050088
David Pursell2ec418a2016-01-20 08:32:08 -080089static const char* serial = nullptr;
Elliott Hughes577e8b42018-04-05 16:12:47 -070090
Elliott Hughes577e8b42018-04-05 16:12:47 -070091static bool g_long_listing = false;
Chris Fries6a999712017-04-04 09:52:47 -050092// Don't resparse files in too-big chunks.
93// libsparse will support INT_MAX, but this results in large allocations, so
94// let's keep it at 1GB to avoid memory pressure on the host.
95static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
Elliott Hughes542370d2018-04-19 19:49:44 -070096static uint64_t sparse_limit = 0;
Colin Crossf8387882012-05-24 17:18:41 -070097static int64_t target_sparse_limit = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080098
Elliott Hughes577e8b42018-04-05 16:12:47 -070099static unsigned g_base_addr = 0x10000000;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800100static boot_img_hdr_v2 g_boot_img_hdr = {};
Elliott Hughes577e8b42018-04-05 16:12:47 -0700101static std::string g_cmdline;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800102static std::string g_dtb_path;
JP Abgrall7b8970c2013-03-07 17:06:41 -0800103
David Zeuthenb6ea4352017-08-07 14:29:26 -0400104static bool g_disable_verity = false;
105static bool g_disable_verification = false;
106
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000107static const std::string convert_fbe_marker_filename("convert_fbe");
108
Tom Cherry9027af02018-09-24 15:48:09 -0700109fastboot::FastBootDriver* fb = nullptr;
110
Rom Lemarchand622810c2013-06-28 09:54:59 -0700111enum fb_buffer_type {
Chris Fries0ea946c2017-04-12 10:25:57 -0500112 FB_BUFFER_FD,
Rom Lemarchand622810c2013-06-28 09:54:59 -0700113 FB_BUFFER_SPARSE,
114};
115
116struct fastboot_buffer {
117 enum fb_buffer_type type;
Elliott Hughesfc797672015-04-07 20:12:50 -0700118 void* data;
119 int64_t sz;
Yifan Hongb10d0672021-02-22 15:06:27 -0800120 unique_fd fd;
David Anderson32e376f2018-08-16 13:43:11 -0700121 int64_t image_size;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700122};
123
David Anderson0debda02018-08-28 13:54:03 -0700124enum class ImageType {
125 // Must be flashed for device to boot into the kernel.
126 BootCritical,
127 // Normal partition to be flashed during "flashall".
128 Normal,
129 // Partition that is never flashed during "flashall".
130 Extra
131};
132
David Anderson32e376f2018-08-16 13:43:11 -0700133struct Image {
Elliott Hughes45964a82017-05-03 22:43:23 -0700134 const char* nickname;
135 const char* img_name;
136 const char* sig_name;
137 const char* part_name;
Hridya Valsarajuf1f0a9c2018-08-02 10:46:21 -0700138 bool optional_if_no_image;
David Anderson0debda02018-08-28 13:54:03 -0700139 ImageType type;
Hridya Valsarajuf1f0a9c2018-08-02 10:46:21 -0700140 bool IsSecondary() const { return nickname == nullptr; }
David Anderson32e376f2018-08-16 13:43:11 -0700141};
142
143static Image images[] = {
Dario Frenic7ea1af2018-05-25 16:07:19 +0100144 // clang-format off
David Anderson0debda02018-08-28 13:54:03 -0700145 { "boot", "boot.img", "boot.sig", "boot", false, ImageType::BootCritical },
146 { nullptr, "boot_other.img", "boot.sig", "boot", true, ImageType::Normal },
147 { "cache", "cache.img", "cache.sig", "cache", true, ImageType::Extra },
148 { "dtbo", "dtbo.img", "dtbo.sig", "dtbo", true, ImageType::BootCritical },
149 { "dts", "dt.img", "dt.sig", "dts", true, ImageType::BootCritical },
150 { "odm", "odm.img", "odm.sig", "odm", true, ImageType::Normal },
Yifan Hongbe78bb62020-07-15 17:07:11 -0700151 { "odm_dlkm", "odm_dlkm.img", "odm_dlkm.sig", "odm_dlkm", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700152 { "product", "product.img", "product.sig", "product", true, ImageType::Normal },
Andrew Scullbe823d72021-01-15 14:37:15 +0000153 { "pvmfw", "pvmfw.img", "pvmfw.sig", "pvmfw", true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700154 { "recovery", "recovery.img", "recovery.sig", "recovery", true, ImageType::BootCritical },
155 { "super", "super.img", "super.sig", "super", true, ImageType::Extra },
156 { "system", "system.img", "system.sig", "system", false, ImageType::Normal },
Justin Yun5d0ac622019-06-26 09:18:03 +0900157 { "system_ext",
158 "system_ext.img", "system_ext.sig",
159 "system_ext",
160 true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700161 { nullptr, "system_other.img", "system.sig", "system", true, ImageType::Normal },
162 { "userdata", "userdata.img", "userdata.sig", "userdata", true, ImageType::Extra },
163 { "vbmeta", "vbmeta.img", "vbmeta.sig", "vbmeta", true, ImageType::BootCritical },
David Anderson166bfef2018-10-15 14:46:59 -0700164 { "vbmeta_system",
165 "vbmeta_system.img",
166 "vbmeta_system.sig",
167 "vbmeta_system",
David Anderson1109c922018-09-17 17:32:54 -0700168 true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700169 { "vendor", "vendor.img", "vendor.sig", "vendor", true, ImageType::Normal },
Steve Muckle36112432019-08-21 11:16:14 -0700170 { "vendor_boot",
171 "vendor_boot.img", "vendor_boot.sig",
172 "vendor_boot",
173 true, ImageType::BootCritical },
Yifan Hong6b1c15c2020-05-12 10:38:53 -0700174 { "vendor_dlkm",
175 "vendor_dlkm.img", "vendor_dlkm.sig",
176 "vendor_dlkm",
177 true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700178 { nullptr, "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
Dario Frenic7ea1af2018-05-25 16:07:19 +0100179 // clang-format on
Rom Lemarchand622810c2013-06-28 09:54:59 -0700180};
Brian Swetland2a63bb72009-04-28 16:05:07 -0700181
David Andersone0e693c2018-11-27 20:19:26 -0800182static char* get_android_product_out() {
Elliott Hughes45964a82017-05-03 22:43:23 -0700183 char* dir = getenv("ANDROID_PRODUCT_OUT");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700184 if (dir == nullptr || dir[0] == '\0') {
David Andersone0e693c2018-11-27 20:19:26 -0800185 return nullptr;
186 }
187 return dir;
188}
189
190static std::string find_item_given_name(const std::string& img_name) {
191 char* dir = get_android_product_out();
192 if (!dir) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700193 die("ANDROID_PRODUCT_OUT not set");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700194 }
David Anderson0debda02018-08-28 13:54:03 -0700195 return std::string(dir) + "/" + img_name;
Alex Lightbb9b8a52016-06-29 09:26:44 -0700196}
197
Elliott Hughes29d5d7d2017-05-11 15:05:13 -0700198static std::string find_item(const std::string& item) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700199 for (size_t i = 0; i < arraysize(images); ++i) {
Elliott Hughesd6365a72017-05-08 18:04:49 -0700200 if (images[i].nickname && item == images[i].nickname) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700201 return find_item_given_name(images[i].img_name);
202 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800203 }
204
Elliott Hughesd6365a72017-05-08 18:04:49 -0700205 fprintf(stderr, "unknown partition '%s'\n", item.c_str());
Elliott Hughes45964a82017-05-03 22:43:23 -0700206 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207}
208
Tom Cherry9027af02018-09-24 15:48:09 -0700209double last_start_time;
210
211static void Status(const std::string& message) {
Tom Cherry2217c502020-06-10 09:29:25 -0700212 if (!message.empty()) {
213 static constexpr char kStatusFormat[] = "%-50s ";
214 fprintf(stderr, kStatusFormat, message.c_str());
215 }
Tom Cherry9027af02018-09-24 15:48:09 -0700216 last_start_time = now();
217}
218
219static void Epilog(int status) {
220 if (status) {
221 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
222 die("Command failed");
223 } else {
224 double split = now();
225 fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
226 }
227}
228
229static void InfoMessage(const std::string& info) {
230 fprintf(stderr, "(bootloader) %s\n", info.c_str());
231}
232
Yifan Hong58532df2021-03-22 16:39:13 -0700233static int64_t get_file_size(borrowed_fd fd) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700234 struct stat sb;
Yifan Hong58532df2021-03-22 16:39:13 -0700235 if (fstat(fd.get(), &sb) == -1) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700236 die("could not get file size");
237 }
238 return sb.st_size;
Colin Crossf8387882012-05-24 17:18:41 -0700239}
240
Tom Cherrydfd85df2018-09-20 14:45:05 -0700241bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
242 out->clear();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800243
Tom Cherrydfd85df2018-09-20 14:45:05 -0700244 unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
245 if (fd == -1) {
246 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700247 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248
Tom Cherrydfd85df2018-09-20 14:45:05 -0700249 out->resize(get_file_size(fd));
250 return ReadFully(fd, out->data(), out->size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700251}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800252
Elliott Hughesfc797672015-04-07 20:12:50 -0700253static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
Elliott Hughese1746fd2015-08-10 15:30:54 -0700254 if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
255 return -1;
256 }
257
Scott Anderson13081c62012-04-06 12:39:30 -0700258 // require matching serial number or device path if requested
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800259 // at the command line with the -s option.
JP Abgralla032ded2012-06-06 11:53:33 -0700260 if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
261 strcmp(local_serial, info->device_path) != 0)) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 return 0;
263}
264
Elliott Hughesfc797672015-04-07 20:12:50 -0700265static int match_fastboot(usb_ifc_info* info) {
JP Abgrall7b8970c2013-03-07 17:06:41 -0800266 return match_fastboot_with_serial(info, serial);
267}
268
Elliott Hughesfc797672015-04-07 20:12:50 -0700269static int list_devices_callback(usb_ifc_info* info) {
270 if (match_fastboot_with_serial(info, nullptr) == 0) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800271 std::string serial = info->serial_number;
David Anderson4e058ca2020-05-28 04:39:37 +0000272 std::string interface = info->interface;
273 if (interface.empty()) {
274 interface = "fastboot";
275 }
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700276 if (!info->writable) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800277 serial = UsbNoPermissionsShortHelpText();
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700278 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800279 if (!serial[0]) {
280 serial = "????????????";
281 }
Scott Anderson866b1bd2012-06-04 20:29:11 -0700282 // output compatible with "adb devices"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700283 if (!g_long_listing) {
David Anderson4e058ca2020-05-28 04:39:37 +0000284 printf("%s\t%s", serial.c_str(), interface.c_str());
Scott Anderson13081c62012-04-06 12:39:30 -0700285 } else {
David Anderson4e058ca2020-05-28 04:39:37 +0000286 printf("%-22s %s", serial.c_str(), interface.c_str());
Elliott Hughes1b708d32015-12-11 19:07:01 -0800287 if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
Scott Anderson13081c62012-04-06 12:39:30 -0700288 }
Elliott Hughes1b708d32015-12-11 19:07:01 -0800289 putchar('\n');
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290 }
291
292 return -1;
293}
294
David Pursell2ec418a2016-01-20 08:32:08 -0800295// Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
296// a specific device, otherwise the first USB device found will be used.
297//
Elliott Hughes855cdf82018-04-02 14:24:03 -0700298// If |serial| is non-null but invalid, this exits.
David Pursell2ec418a2016-01-20 08:32:08 -0800299// Otherwise it blocks until the target is available.
300//
301// The returned Transport is a singleton, so multiple calls to this function will return the same
302// object, and the caller should not attempt to delete the returned Transport.
David Pursell0b156632015-10-30 11:22:01 -0700303static Transport* open_device() {
David Pursell2ec418a2016-01-20 08:32:08 -0800304 bool announce = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800305
David Pursell4601c972016-02-05 15:35:09 -0800306 Socket::Protocol protocol = Socket::Protocol::kTcp;
David Pursell2ec418a2016-01-20 08:32:08 -0800307 std::string host;
David Pursell4601c972016-02-05 15:35:09 -0800308 int port = 0;
309 if (serial != nullptr) {
310 const char* net_address = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800311
David Pursell4601c972016-02-05 15:35:09 -0800312 if (android::base::StartsWith(serial, "tcp:")) {
313 protocol = Socket::Protocol::kTcp;
314 port = tcp::kDefaultPort;
315 net_address = serial + strlen("tcp:");
316 } else if (android::base::StartsWith(serial, "udp:")) {
317 protocol = Socket::Protocol::kUdp;
318 port = udp::kDefaultPort;
319 net_address = serial + strlen("udp:");
320 }
321
322 if (net_address != nullptr) {
323 std::string error;
324 if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700325 die("invalid network address '%s': %s\n", net_address, error.c_str());
David Pursell4601c972016-02-05 15:35:09 -0800326 }
David Pursell2ec418a2016-01-20 08:32:08 -0800327 }
328 }
329
David Anderson1d887432018-08-27 16:47:32 -0700330 Transport* transport = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800331 while (true) {
332 if (!host.empty()) {
333 std::string error;
David Pursell4601c972016-02-05 15:35:09 -0800334 if (protocol == Socket::Protocol::kTcp) {
335 transport = tcp::Connect(host, port, &error).release();
336 } else if (protocol == Socket::Protocol::kUdp) {
337 transport = udp::Connect(host, port, &error).release();
338 }
339
David Pursell2ec418a2016-01-20 08:32:08 -0800340 if (transport == nullptr && announce) {
341 fprintf(stderr, "error: %s\n", error.c_str());
342 }
343 } else {
344 transport = usb_open(match_fastboot);
345 }
346
347 if (transport != nullptr) {
348 return transport;
349 }
350
David Pursell0b156632015-10-30 11:22:01 -0700351 if (announce) {
David Pursell2ec418a2016-01-20 08:32:08 -0800352 announce = false;
Elliott Hughesb46964f2015-08-19 17:49:45 -0700353 fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800355 std::this_thread::sleep_for(std::chrono::milliseconds(1));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800356 }
357}
358
Elliott Hughesfc797672015-04-07 20:12:50 -0700359static void list_devices() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800360 // We don't actually open a USB device here,
361 // just getting our callback called so we can
362 // list all the connected devices.
363 usb_open(list_devices_callback);
364}
365
Elliott Hughesd6365a72017-05-08 18:04:49 -0700366static void syntax_error(const char* fmt, ...) {
367 fprintf(stderr, "fastboot: usage: ");
368
369 va_list ap;
370 va_start(ap, fmt);
371 vfprintf(stderr, fmt, ap);
372 va_end(ap);
373
374 fprintf(stderr, "\n");
375 exit(1);
376}
377
378static int show_help() {
379 // clang-format off
380 fprintf(stdout,
Elliott Hughes07fc6822018-05-24 16:36:05 -0700381// 1 2 3 4 5 6 7 8
382// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
Elliott Hughesb76188f2018-04-03 13:30:18 -0700383 "usage: fastboot [OPTION...] COMMAND...\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800384 "\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700385 "flashing:\n"
386 " update ZIP Flash all partitions from an update.zip package.\n"
387 " flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
388 " On A/B devices, flashed slot is set as active.\n"
389 " Secondary images may be flashed to inactive slot.\n"
Elliott Hughes07fc6822018-05-24 16:36:05 -0700390 " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
391 " $ANDROID_PRODUCT_OUT if no filename is given.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700392 "\n"
393 "basics:\n"
394 " devices [-l] List devices in bootloader (-l: with device paths).\n"
395 " getvar NAME Display given bootloader variable.\n"
396 " reboot [bootloader] Reboot device.\n"
397 "\n"
398 "locking/unlocking:\n"
399 " flashing lock|unlock Lock/unlock partitions for flashing\n"
400 " flashing lock_critical|unlock_critical\n"
401 " Lock/unlock 'critical' bootloader partitions.\n"
402 " flashing get_unlock_ability\n"
403 " Check whether unlocking is allowed (1) or not(0).\n"
404 "\n"
405 "advanced:\n"
406 " erase PARTITION Erase a flash partition.\n"
407 " format[:FS_TYPE[:SIZE]] PARTITION\n"
408 " Format a flash partition.\n"
409 " set_active SLOT Set the active slot.\n"
410 " oem [COMMAND...] Execute OEM-specific command.\n"
David Anderson1d504e32019-01-15 14:38:20 -0800411 " gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
David Anderson7c84b9f2019-06-27 22:15:29 -0700412 " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
413 " contain an empty set of default dynamic partitions.\n"
Luca Stefani173667b2021-04-12 19:16:43 +0200414 " create-logical-partition NAME SIZE\n"
415 " Create a logical partition with the given name and\n"
416 " size, in the super partition.\n"
417 " delete-logical-partition NAME\n"
418 " Delete a logical partition with the given name.\n"
419 " resize-logical-partition NAME SIZE\n"
420 " Change the size of the named logical partition.\n"
David Andersonab8f4662019-10-21 16:45:59 -0700421 " snapshot-update cancel On devices that support snapshot-based updates, cancel\n"
422 " an in-progress update. This may make the device\n"
423 " unbootable until it is reflashed.\n"
David Anderson220ddb12019-10-31 18:02:41 -0700424 " snapshot-update merge On devices that support snapshot-based updates, finish\n"
425 " an in-progress update if it is in the \"merging\"\n"
426 " phase.\n"
Yifan Hongbcd27702021-02-16 19:37:32 -0800427 " fetch PARTITION Fetch a partition image from the device."
Elliott Hughesb76188f2018-04-03 13:30:18 -0700428 "\n"
429 "boot image:\n"
430 " boot KERNEL [RAMDISK [SECOND]]\n"
431 " Download and boot kernel from RAM.\n"
432 " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
433 " Create boot image and flash it.\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800434 " --dtb DTB Specify path to DTB for boot image header version 2.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700435 " --cmdline CMDLINE Override kernel command line.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700436 " --base ADDRESS Set kernel base address (default: 0x10000000).\n"
437 " --kernel-offset Set kernel offset (default: 0x00008000).\n"
438 " --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
439 " --tags-offset Set tags offset (default: 0x00000100).\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800440 " --dtb-offset Set dtb offset (default: 0x01100000).\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700441 " --page-size BYTES Set flash page size (default: 2048).\n"
442 " --header-version VERSION Set boot image header version.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700443 " --os-version MAJOR[.MINOR[.PATCH]]\n"
444 " Set boot image OS version (default: 0.0.0).\n"
445 " --os-patch-level YYYY-MM-DD\n"
446 " Set boot image OS security patch level.\n"
447 // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
Elliott Hughesb76188f2018-04-03 13:30:18 -0700448 "\n"
Elliott Hughes2e9b7792018-04-04 13:36:44 -0700449 // TODO: what device(s) used this? is there any documentation?
Elliott Hughesb76188f2018-04-03 13:30:18 -0700450 //" continue Continue with autoboot.\n"
451 //"\n"
452 "Android Things:\n"
453 " stage IN_FILE Sends given file to stage for the next command.\n"
454 " get_staged OUT_FILE Writes data staged by the last command to a file.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800455 "\n"
456 "options:\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700457 " -w Wipe userdata.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700458 " -s SERIAL Specify a USB device.\n"
459 " -s tcp|udp:HOST[:PORT] Specify a network device.\n"
Elliott Hughes542370d2018-04-19 19:49:44 -0700460 " -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
David Anderson89569642018-11-16 15:53:35 -0800461 " --force Force a flash operation that may be unsafe.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700462 " --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
463 " non-current slot (default: current active slot).\n"
464 " --set-active[=SLOT] Sets the active slot before rebooting.\n"
465 " --skip-secondary Don't flash secondary slots in flashall/update.\n"
466 " --skip-reboot Don't reboot device after flashing.\n"
467 " --disable-verity Sets disable-verity when flashing vbmeta.\n"
468 " --disable-verification Sets disable-verification when flashing vbmeta.\n"
Jaegeuk Kim638d05e2020-11-09 08:54:13 -0800469 " --fs-options=OPTION[,OPTION]\n"
470 " Enable filesystem features. OPTION supports casefold, projid, compress\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000471#if !defined(_WIN32)
Elliott Hughesb76188f2018-04-03 13:30:18 -0700472 " --wipe-and-use-fbe Enable file-based encryption, wiping userdata.\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000473#endif
Elliott Hughesb76188f2018-04-03 13:30:18 -0700474 // TODO: remove --unbuffered?
475 " --unbuffered Don't buffer input or output.\n"
476 " --verbose, -v Verbose output.\n"
477 " --version Display version.\n"
478 " --help, -h Show this message.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 );
Yifan Hongbcd27702021-02-16 19:37:32 -0800480 // clang-format on
Elliott Hughesd6365a72017-05-08 18:04:49 -0700481 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482}
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000483
Tom Cherrydfd85df2018-09-20 14:45:05 -0700484static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
485 const std::string& second_stage) {
486 std::vector<char> kernel_data;
487 if (!ReadFileToVector(kernel, &kernel_data)) {
488 die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
489 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800490
Elliott Hughesfc797672015-04-07 20:12:50 -0700491 // Is this actually a boot image?
Steve Muckle15303f22020-03-18 14:55:06 -0700492 if (kernel_data.size() < sizeof(boot_img_hdr_v3)) {
Elliott Hughesaaa3b6b2018-01-18 16:08:24 -0800493 die("cannot load '%s': too short", kernel.c_str());
494 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700495 if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
Elliott Hughes577e8b42018-04-05 16:12:47 -0700496 if (!g_cmdline.empty()) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800497 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
Elliott Hughes577e8b42018-04-05 16:12:47 -0700498 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800499
Elliott Hughes4089d342017-10-27 14:21:12 -0700500 if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800501
Tom Cherrydfd85df2018-09-20 14:45:05 -0700502 return kernel_data;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 }
504
Tom Cherrydfd85df2018-09-20 14:45:05 -0700505 std::vector<char> ramdisk_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700506 if (!ramdisk.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700507 if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
508 die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
509 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510 }
511
Tom Cherrydfd85df2018-09-20 14:45:05 -0700512 std::vector<char> second_stage_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700513 if (!second_stage.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700514 if (!ReadFileToVector(second_stage, &second_stage_data)) {
515 die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
516 }
Jeremy Compostellaa42adff2014-07-17 17:17:54 +0200517 }
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800518
519 std::vector<char> dtb_data;
520 if (!g_dtb_path.empty()) {
Steve Muckle15303f22020-03-18 14:55:06 -0700521 if (g_boot_img_hdr.header_version != 2) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800522 die("Argument dtb not supported for boot image header version %d\n",
523 g_boot_img_hdr.header_version);
524 }
525 if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
526 die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
527 }
528 }
529
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530 fprintf(stderr,"creating boot image...\n");
Elliott Hughesd6365a72017-05-08 18:04:49 -0700531
Tom Cherrydfd85df2018-09-20 14:45:05 -0700532 std::vector<char> out;
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800533 mkbootimg(kernel_data, ramdisk_data, second_stage_data, dtb_data, g_base_addr, g_boot_img_hdr,
534 &out);
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800535
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800536 if (!g_cmdline.empty()) {
537 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(out.data()), g_cmdline);
538 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700539 fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700540 return out;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541}
542
Tom Cherrydfd85df2018-09-20 14:45:05 -0700543static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
544 std::vector<char>* out) {
Elliott Hughesb4074142020-09-15 14:26:17 -0700545 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700546 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700547 fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
548 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800549 }
550
Elliott Hughesb4074142020-09-15 14:26:17 -0700551 if (zip_entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
552 die("entry '%s' is too large: %" PRIu64, entry_name.c_str(), zip_entry.uncompressed_length);
553 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700554 out->resize(zip_entry.uncompressed_length);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800555
Tom Cherrydfd85df2018-09-20 14:45:05 -0700556 fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
557 out->size() / 1024 / 1024);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558
Tom Cherrydfd85df2018-09-20 14:45:05 -0700559 int error = ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()),
560 out->size());
561 if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000562
Tom Cherrydfd85df2018-09-20 14:45:05 -0700563 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564}
565
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700566#if defined(_WIN32)
567
568// TODO: move this to somewhere it can be shared.
569
570#include <windows.h>
571
572// Windows' tmpfile(3) requires administrator rights because
573// it creates temporary files in the root directory.
574static FILE* win32_tmpfile() {
575 char temp_path[PATH_MAX];
576 DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
577 if (nchars == 0 || nchars >= sizeof(temp_path)) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700578 die("GetTempPath failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700579 }
580
581 char filename[PATH_MAX];
582 if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700583 die("GetTempFileName failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700584 }
585
586 return fopen(filename, "w+bTD");
587}
588
589#define tmpfile win32_tmpfile
590
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000591static std::string make_temporary_directory() {
Elliott Hughes4089d342017-10-27 14:21:12 -0700592 die("make_temporary_directory not supported under Windows, sorry!");
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000593}
594
Elliott Hughes855cdf82018-04-02 14:24:03 -0700595static int make_temporary_fd(const char* /*what*/) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700596 // TODO: reimplement to avoid leaking a FILE*.
597 return fileno(tmpfile());
598}
599
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000600#else
601
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700602static std::string make_temporary_template() {
603 const char* tmpdir = getenv("TMPDIR");
604 if (tmpdir == nullptr) tmpdir = P_tmpdir;
605 return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
606}
607
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000608static std::string make_temporary_directory() {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700609 std::string result(make_temporary_template());
610 if (mkdtemp(&result[0]) == nullptr) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700611 die("unable to create temporary directory with template %s: %s",
612 result.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000613 }
614 return result;
615}
616
Elliott Hughes855cdf82018-04-02 14:24:03 -0700617static int make_temporary_fd(const char* what) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700618 std::string path_template(make_temporary_template());
619 int fd = mkstemp(&path_template[0]);
620 if (fd == -1) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700621 die("failed to create temporary file for %s with template %s: %s\n",
622 path_template.c_str(), what, strerror(errno));
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700623 }
624 unlink(path_template.c_str());
625 return fd;
626}
627
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700628#endif
629
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000630static std::string create_fbemarker_tmpdir() {
631 std::string dir = make_temporary_directory();
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000632 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
633 int fd = open(marker_file.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0666);
634 if (fd == -1) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700635 die("unable to create FBE marker file %s locally: %s",
636 marker_file.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000637 }
638 close(fd);
639 return dir;
640}
641
642static void delete_fbemarker_tmpdir(const std::string& dir) {
643 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
644 if (unlink(marker_file.c_str()) == -1) {
645 fprintf(stderr, "Unable to delete FBE marker file %s locally: %d, %s\n",
646 marker_file.c_str(), errno, strerror(errno));
647 return;
648 }
649 if (rmdir(dir.c_str()) == -1) {
650 fprintf(stderr, "Unable to delete FBE marker directory %s locally: %d, %s\n",
651 dir.c_str(), errno, strerror(errno));
652 return;
653 }
654}
655
Yifan Hongb10d0672021-02-22 15:06:27 -0800656static unique_fd unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700657 unique_fd fd(make_temporary_fd(entry_name));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700658
Elliott Hughesb4074142020-09-15 14:26:17 -0700659 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700660 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700661 fprintf(stderr, "archive does not contain '%s'\n", entry_name);
David Andersoncf444f32018-08-29 14:15:49 -0700662 errno = ENOENT;
Yifan Hongb10d0672021-02-22 15:06:27 -0800663 return unique_fd();
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000664 }
665
Elliott Hughesb4074142020-09-15 14:26:17 -0700666 fprintf(stderr, "extracting %s (%" PRIu64 " MB) to disk...", entry_name,
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700667 zip_entry.uncompressed_length / 1024 / 1024);
Elliott Hughes23af1122017-11-10 08:42:17 -0800668 double start = now();
Yifan Hong58532df2021-03-22 16:39:13 -0700669 int error = ExtractEntryToFile(zip, &zip_entry, fd.get());
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700670 if (error != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800671 die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700672 }
673
Yifan Hong58532df2021-03-22 16:39:13 -0700674 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800675 die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
Elliott Hughes4089d342017-10-27 14:21:12 -0700676 }
677
Elliott Hughes23af1122017-11-10 08:42:17 -0800678 fprintf(stderr, " took %.3fs\n", now() - start);
679
Yifan Hongb10d0672021-02-22 15:06:27 -0800680 return fd;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700681}
682
Andrew Chantd64b9882021-04-06 12:48:27 -0700683static bool CheckRequirement(const std::string& cur_product, const std::string& var,
Tom Cherry4aa60b32018-09-05 15:11:44 -0700684 const std::string& product, bool invert,
685 const std::vector<std::string>& options) {
686 Status("Checking '" + var + "'");
Elliott Hughes5620d222018-03-28 08:20:00 -0700687
Tom Cherry4aa60b32018-09-05 15:11:44 -0700688 double start = now();
689
690 if (!product.empty()) {
691 if (product != cur_product) {
692 double split = now();
693 fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
694 cur_product.c_str(), product.c_str(), (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700695 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700696 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800697 }
Tom Cherry4aa60b32018-09-05 15:11:44 -0700698
699 std::string var_value;
Tom Cherry9027af02018-09-24 15:48:09 -0700700 if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700701 fprintf(stderr, "FAILED\n\n");
Tom Cherry9027af02018-09-24 15:48:09 -0700702 fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(),
703 fb->Error().c_str());
Andrew Chantd64b9882021-04-06 12:48:27 -0700704 return false;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700705 }
706
707 bool match = false;
708 for (const auto& option : options) {
709 if (option == var_value || (option.back() == '*' &&
710 !var_value.compare(0, option.length() - 1, option, 0,
711 option.length() - 1))) {
712 match = true;
713 break;
714 }
715 }
716
717 if (invert) {
718 match = !match;
719 }
720
721 if (match) {
722 double split = now();
723 fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700724 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700725 }
726
727 fprintf(stderr, "FAILED\n\n");
728 fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
729 fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
730 for (auto it = std::next(options.begin()); it != options.end(); ++it) {
731 fprintf(stderr, " or '%s'", it->c_str());
732 }
733 fprintf(stderr, ".\n\n");
Andrew Chantd64b9882021-04-06 12:48:27 -0700734 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735}
736
Tom Cherry4aa60b32018-09-05 15:11:44 -0700737bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
738 bool* invert, std::vector<std::string>* options) {
Elliott Hughes5620d222018-03-28 08:20:00 -0700739 // "require product=alpha|beta|gamma"
740 // "require version-bootloader=1234"
741 // "require-for-product:gamma version-bootloader=istanbul|constantinople"
742 // "require partition-exists=vendor"
Tom Cherry4aa60b32018-09-05 15:11:44 -0700743 *product = "";
744 *invert = false;
Elliott Hughes5620d222018-03-28 08:20:00 -0700745
Tom Cherry4aa60b32018-09-05 15:11:44 -0700746 auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
747 auto require_product_regex =
748 std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
749 std::smatch match_results;
750
751 if (std::regex_match(line, match_results, require_reject_regex)) {
752 *invert = Trim(match_results[1]) == "reject";
753 } else if (std::regex_match(line, match_results, require_product_regex)) {
754 *product = match_results[1];
755 } else {
756 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757 }
758
Tom Cherry4aa60b32018-09-05 15:11:44 -0700759 *name = match_results[2];
Elliott Hughes253c18d2015-03-18 22:47:09 -0700760 // Work around an unfortunate name mismatch.
Tom Cherry4aa60b32018-09-05 15:11:44 -0700761 if (*name == "board") {
762 *name = "product";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800763 }
764
Tom Cherry4aa60b32018-09-05 15:11:44 -0700765 auto raw_options = Split(match_results[3], "|");
766 for (const auto& option : raw_options) {
767 auto trimmed_option = Trim(option);
768 options->emplace_back(trimmed_option);
769 }
770
771 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800772}
773
Tom Cherry4aa60b32018-09-05 15:11:44 -0700774// "require partition-exists=x" is a special case, added because of the trouble we had when
775// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
776// missing out new partitions. A device with new partitions can use "partition-exists" to
777// override the fields `optional_if_no_image` in the `images` array.
778static void HandlePartitionExists(const std::vector<std::string>& options) {
779 const std::string& partition_name = options[0];
780 std::string has_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700781 if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
Tom Cherry4aa60b32018-09-05 15:11:44 -0700782 (has_slot != "yes" && has_slot != "no")) {
783 die("device doesn't have required partition %s!", partition_name.c_str());
784 }
785 bool known_partition = false;
786 for (size_t i = 0; i < arraysize(images); ++i) {
787 if (images[i].nickname && images[i].nickname == partition_name) {
788 images[i].optional_if_no_image = false;
789 known_partition = true;
790 }
791 }
792 if (!known_partition) {
793 die("device requires partition %s which is not known to this version of fastboot",
794 partition_name.c_str());
795 }
796}
797
Andrew Chantd64b9882021-04-06 12:48:27 -0700798static void CheckRequirements(const std::string& data, bool force_flash) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700799 std::string cur_product;
Tom Cherry9027af02018-09-24 15:48:09 -0700800 if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
801 fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700802 }
803
804 auto lines = Split(data, "\n");
805 for (const auto& line : lines) {
806 if (line.empty()) {
807 continue;
808 }
809
810 std::string name;
811 std::string product;
812 bool invert;
813 std::vector<std::string> options;
814
815 if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
816 fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
817 continue;
818 }
819 if (name == "partition-exists") {
820 HandlePartitionExists(options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800821 } else {
Andrew Chantd64b9882021-04-06 12:48:27 -0700822 bool met = CheckRequirement(cur_product, name, product, invert, options);
823 if (!met) {
824 if (!force_flash) {
825 die("requirements not met!");
826 } else {
827 fprintf(stderr, "requirements not met! but proceeding due to --force\n");
828 }
829 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800830 }
831 }
832}
833
Tom Cherry9027af02018-09-24 15:48:09 -0700834static void DisplayVarOrError(const std::string& label, const std::string& var) {
835 std::string value;
836
837 if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
838 Status("getvar:" + var);
839 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
840 return;
841 }
842 fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
843}
844
845static void DumpInfo() {
846 fprintf(stderr, "--------------------------------------------\n");
847 DisplayVarOrError("Bootloader Version...", "version-bootloader");
848 DisplayVarOrError("Baseband Version.....", "version-baseband");
849 DisplayVarOrError("Serial Number........", "serialno");
850 fprintf(stderr, "--------------------------------------------\n");
851
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800852}
853
Tao Bao41cf35f2018-04-24 10:54:21 -0700854static struct sparse_file** load_sparse_files(int fd, int64_t max_size) {
Mohamad Ayyash80cc1f62015-03-31 12:09:29 -0700855 struct sparse_file* s = sparse_file_import_auto(fd, false, true);
Elliott Hughes4089d342017-10-27 14:21:12 -0700856 if (!s) die("cannot sparse read file");
Colin Crossf8387882012-05-24 17:18:41 -0700857
Tao Bao41cf35f2018-04-24 10:54:21 -0700858 if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
859 die("invalid max size %" PRId64, max_size);
860 }
861
Elliott Hughesfc797672015-04-07 20:12:50 -0700862 int files = sparse_file_resparse(s, max_size, nullptr, 0);
Elliott Hughes4089d342017-10-27 14:21:12 -0700863 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700864
Elliott Hughes253c18d2015-03-18 22:47:09 -0700865 sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
Elliott Hughes4089d342017-10-27 14:21:12 -0700866 if (!out_s) die("Failed to allocate sparse file array");
Colin Crossf8387882012-05-24 17:18:41 -0700867
868 files = sparse_file_resparse(s, max_size, out_s, files);
Elliott Hughes4089d342017-10-27 14:21:12 -0700869 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700870
871 return out_s;
872}
873
Yifan Hongbcd27702021-02-16 19:37:32 -0800874static uint64_t get_uint_var(const char* var_name) {
875 std::string value_str;
876 if (fb->GetVar(var_name, &value_str) != fastboot::SUCCESS || value_str.empty()) {
877 verbose("target didn't report %s", var_name);
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700878 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700879 }
880
Elliott Hughes77c0e662015-11-02 15:51:12 -0800881 // Some bootloaders (angler, for example) send spurious whitespace too.
Yifan Hongbcd27702021-02-16 19:37:32 -0800882 value_str = android::base::Trim(value_str);
Elliott Hughes77c0e662015-11-02 15:51:12 -0800883
Yifan Hongbcd27702021-02-16 19:37:32 -0800884 uint64_t value;
885 if (!android::base::ParseUint(value_str, &value)) {
886 fprintf(stderr, "couldn't parse %s '%s'\n", var_name, value_str.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700887 return 0;
888 }
Yifan Hongbcd27702021-02-16 19:37:32 -0800889 if (value > 0) verbose("target reported %s of %" PRId64 " bytes", var_name, value);
890 return value;
Colin Crossf8387882012-05-24 17:18:41 -0700891}
892
Aaron Wisnerdb511202018-06-26 15:38:35 -0500893static int64_t get_sparse_limit(int64_t size) {
Elliott Hughes542370d2018-04-19 19:49:44 -0700894 int64_t limit = sparse_limit;
895 if (limit == 0) {
896 // Unlimited, so see what the target device's limit is.
897 // TODO: shouldn't we apply this limit even if you've used -S?
Colin Crossf8387882012-05-24 17:18:41 -0700898 if (target_sparse_limit == -1) {
Yifan Hongbcd27702021-02-16 19:37:32 -0800899 target_sparse_limit = static_cast<int64_t>(get_uint_var("max-download-size"));
Colin Crossf8387882012-05-24 17:18:41 -0700900 }
901 if (target_sparse_limit > 0) {
902 limit = target_sparse_limit;
903 } else {
Colin Cross0bbfb392012-07-24 18:05:21 -0700904 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700905 }
906 }
907
908 if (size > limit) {
Chris Fries6a999712017-04-04 09:52:47 -0500909 return std::min(limit, RESPARSE_LIMIT);
Colin Crossf8387882012-05-24 17:18:41 -0700910 }
911
912 return 0;
913}
914
Yifan Hongb10d0672021-02-22 15:06:27 -0800915static bool load_buf_fd(unique_fd fd, struct fastboot_buffer* buf) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700916 int64_t sz = get_file_size(fd);
917 if (sz == -1) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700918 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700919 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -0700920
Yifan Hong58532df2021-03-22 16:39:13 -0700921 if (sparse_file* s = sparse_file_import(fd.get(), false, false)) {
David Anderson32e376f2018-08-16 13:43:11 -0700922 buf->image_size = sparse_file_len(s, false, false);
923 sparse_file_destroy(s);
924 } else {
925 buf->image_size = sz;
926 }
927
Yifan Hong58532df2021-03-22 16:39:13 -0700928 lseek(fd.get(), 0, SEEK_SET);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500929 int64_t limit = get_sparse_limit(sz);
Yifan Honge9f067b2021-03-22 16:55:39 -0700930 buf->fd = std::move(fd);
Colin Crossf8387882012-05-24 17:18:41 -0700931 if (limit) {
Yifan Honge9f067b2021-03-22 16:55:39 -0700932 sparse_file** s = load_sparse_files(buf->fd.get(), limit);
Elliott Hughesfc797672015-04-07 20:12:50 -0700933 if (s == nullptr) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700934 return false;
Colin Crossf8387882012-05-24 17:18:41 -0700935 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700936 buf->type = FB_BUFFER_SPARSE;
937 buf->data = s;
Colin Crossf8387882012-05-24 17:18:41 -0700938 } else {
Chris Fries0ea946c2017-04-12 10:25:57 -0500939 buf->type = FB_BUFFER_FD;
940 buf->data = nullptr;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000941 buf->sz = sz;
Colin Crossf8387882012-05-24 17:18:41 -0700942 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700943
Elliott Hughes53ec4952016-05-11 12:39:27 -0700944 return true;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700945}
946
Aaron Wisnerdb511202018-06-26 15:38:35 -0500947static bool load_buf(const char* fname, struct fastboot_buffer* buf) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500948 unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
949
Elliott Hughes53ec4952016-05-11 12:39:27 -0700950 if (fd == -1) {
951 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700952 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500953
954 struct stat s;
Yifan Hong58532df2021-03-22 16:39:13 -0700955 if (fstat(fd.get(), &s)) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500956 return false;
957 }
958 if (!S_ISREG(s.st_mode)) {
959 errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
960 return false;
961 }
962
Yifan Hongb10d0672021-02-22 15:06:27 -0800963 return load_buf_fd(std::move(fd), buf);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700964}
965
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800966static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf, bool vbmeta_in_boot) {
David Zeuthenb6ea4352017-08-07 14:29:26 -0400967 // Buffer needs to be at least the size of the VBMeta struct which
968 // is 256 bytes.
969 if (buf->sz < 256) {
970 return;
971 }
972
David Zeuthenb6ea4352017-08-07 14:29:26 -0400973 std::string data;
974 if (!android::base::ReadFdToString(buf->fd, &data)) {
975 die("Failed reading from vbmeta");
976 }
977
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800978 uint64_t vbmeta_offset = 0;
979 if (vbmeta_in_boot) {
980 // Tries to locate top-level vbmeta from boot.img footer.
981 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
982 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
983 die("Failed to find AVB_FOOTER at offset: %" PRId64, footer_offset);
984 }
985 const AvbFooter* footer = reinterpret_cast<const AvbFooter*>(data.c_str() + footer_offset);
986 vbmeta_offset = be64toh(footer->vbmeta_offset);
987 }
988 // Ensures there is AVB_MAGIC at vbmeta_offset.
989 if (0 != data.compare(vbmeta_offset, AVB_MAGIC_LEN, AVB_MAGIC)) {
990 die("Failed to find AVB_MAGIC at offset: %" PRId64, vbmeta_offset);
991 }
992
993 fprintf(stderr, "Rewriting vbmeta struct at offset: %" PRId64 "\n", vbmeta_offset);
994
David Zeuthenb6ea4352017-08-07 14:29:26 -0400995 // There's a 32-bit big endian |flags| field at offset 120 where
996 // bit 0 corresponds to disable-verity and bit 1 corresponds to
997 // disable-verification.
998 //
999 // See external/avb/libavb/avb_vbmeta_image.h for the layout of
1000 // the VBMeta struct.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001001 uint64_t flags_offset = 123 + vbmeta_offset;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001002 if (g_disable_verity) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001003 data[flags_offset] |= 0x01;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001004 }
1005 if (g_disable_verification) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001006 data[flags_offset] |= 0x02;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001007 }
1008
Yifan Hongb10d0672021-02-22 15:06:27 -08001009 unique_fd fd(make_temporary_fd("vbmeta rewriting"));
David Zeuthenb6ea4352017-08-07 14:29:26 -04001010 if (!android::base::WriteStringToFd(data, fd)) {
1011 die("Failed writing to modified vbmeta");
1012 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001013 buf->fd = std::move(fd);
Yifan Hong58532df2021-03-22 16:39:13 -07001014 lseek(buf->fd.get(), 0, SEEK_SET);
David Zeuthenb6ea4352017-08-07 14:29:26 -04001015}
1016
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001017static bool has_vbmeta_partition() {
1018 std::string partition_type;
1019 return fb->GetVar("partition-type:vbmeta", &partition_type) == fastboot::SUCCESS ||
1020 fb->GetVar("partition-type:vbmeta_a", &partition_type) == fastboot::SUCCESS ||
1021 fb->GetVar("partition-type:vbmeta_b", &partition_type) == fastboot::SUCCESS;
1022}
1023
Michael Bestasa495be72020-11-06 17:58:28 +02001024static bool is_logical(const std::string& partition) {
1025 std::string value;
1026 return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1027}
1028
Steve Muckle3af575b2020-06-18 17:02:15 -07001029static std::string fb_fix_numeric_var(std::string var) {
1030 // Some bootloaders (angler, for example), send spurious leading whitespace.
1031 var = android::base::Trim(var);
1032 // Some bootloaders (hammerhead, for example) use implicit hex.
1033 // This code used to use strtol with base 16.
1034 if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
1035 return var;
1036}
1037
Yifan Hongbcd27702021-02-16 19:37:32 -08001038static uint64_t get_partition_size(const std::string& partition) {
Steve Muckle3af575b2020-06-18 17:02:15 -07001039 std::string partition_size_str;
1040 if (fb->GetVar("partition-size:" + partition, &partition_size_str) != fastboot::SUCCESS) {
Michael Bestasa495be72020-11-06 17:58:28 +02001041 if (!is_logical(partition)) {
1042 return 0;
1043 }
Yifan Hong60de9692021-02-17 13:51:54 -08001044 die("cannot get partition size for %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001045 }
1046
1047 partition_size_str = fb_fix_numeric_var(partition_size_str);
Yifan Hongbcd27702021-02-16 19:37:32 -08001048 uint64_t partition_size;
1049 if (!android::base::ParseUint(partition_size_str, &partition_size)) {
Michael Bestasa495be72020-11-06 17:58:28 +02001050 if (!is_logical(partition)) {
1051 return 0;
1052 }
Steve Muckle3af575b2020-06-18 17:02:15 -07001053 die("Couldn't parse partition size '%s'.", partition_size_str.c_str());
1054 }
Yifan Hongbcd27702021-02-16 19:37:32 -08001055 return partition_size;
1056}
1057
1058static void copy_boot_avb_footer(const std::string& partition, struct fastboot_buffer* buf) {
1059 if (buf->sz < AVB_FOOTER_SIZE) {
1060 return;
1061 }
1062
Steve Muckle3af575b2020-06-18 17:02:15 -07001063 std::string data;
1064 if (!android::base::ReadFdToString(buf->fd, &data)) {
1065 die("Failed reading from boot");
1066 }
1067
1068 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
1069 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
1070 return;
1071 }
Michael Bestasa495be72020-11-06 17:58:28 +02001072 // If overflows and negative, it should be < buf->sz.
1073 int64_t partition_size = static_cast<int64_t>(get_partition_size(partition));
1074
1075 if (partition_size == buf->sz) {
1076 return;
1077 }
1078 if (partition_size < buf->sz) {
1079 die("boot partition is smaller than boot image");
1080 }
Steve Muckle3af575b2020-06-18 17:02:15 -07001081
Yifan Hongb10d0672021-02-22 15:06:27 -08001082 unique_fd fd(make_temporary_fd("boot rewriting"));
Steve Muckle3af575b2020-06-18 17:02:15 -07001083 if (!android::base::WriteStringToFd(data, fd)) {
1084 die("Failed writing to modified boot");
1085 }
Yifan Hong58532df2021-03-22 16:39:13 -07001086 lseek(fd.get(), partition_size - AVB_FOOTER_SIZE, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001087 if (!android::base::WriteStringToFd(data.substr(footer_offset), fd)) {
1088 die("Failed copying AVB footer in boot");
1089 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001090 buf->fd = std::move(fd);
Steve Muckle3af575b2020-06-18 17:02:15 -07001091 buf->sz = partition_size;
Yifan Hong58532df2021-03-22 16:39:13 -07001092 lseek(buf->fd.get(), 0, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001093}
1094
Elliott Hughes5620d222018-03-28 08:20:00 -07001095static void flash_buf(const std::string& partition, struct fastboot_buffer *buf)
Rom Lemarchand622810c2013-06-28 09:54:59 -07001096{
Elliott Hughes253c18d2015-03-18 22:47:09 -07001097 sparse_file** s;
Rom Lemarchand622810c2013-06-28 09:54:59 -07001098
Steve Muckle3af575b2020-06-18 17:02:15 -07001099 if (partition == "boot" || partition == "boot_a" || partition == "boot_b") {
1100 copy_boot_avb_footer(partition, buf);
1101 }
1102
David Zeuthenb6ea4352017-08-07 14:29:26 -04001103 // Rewrite vbmeta if that's what we're flashing and modification has been requested.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001104 if (g_disable_verity || g_disable_verification) {
1105 if (partition == "vbmeta" || partition == "vbmeta_a" || partition == "vbmeta_b") {
1106 rewrite_vbmeta_buffer(buf, false /* vbmeta_in_boot */);
1107 } else if (!has_vbmeta_partition() &&
1108 (partition == "boot" || partition == "boot_a" || partition == "boot_b")) {
1109 rewrite_vbmeta_buffer(buf, true /* vbmeta_in_boot */ );
1110 }
David Zeuthenb6ea4352017-08-07 14:29:26 -04001111 }
1112
Rom Lemarchand622810c2013-06-28 09:54:59 -07001113 switch (buf->type) {
Josh Gao9da9ac52016-01-19 14:50:18 -08001114 case FB_BUFFER_SPARSE: {
1115 std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
Elliott Hughes253c18d2015-03-18 22:47:09 -07001116 s = reinterpret_cast<sparse_file**>(buf->data);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001117 while (*s) {
Elliott Hughesfc797672015-04-07 20:12:50 -07001118 int64_t sz = sparse_file_len(*s, true, false);
Josh Gao9da9ac52016-01-19 14:50:18 -08001119 sparse_files.emplace_back(*s, sz);
1120 ++s;
1121 }
1122
1123 for (size_t i = 0; i < sparse_files.size(); ++i) {
1124 const auto& pair = sparse_files[i];
Tom Cherry9027af02018-09-24 15:48:09 -07001125 fb->FlashPartition(partition, pair.first, pair.second, i + 1, sparse_files.size());
Rom Lemarchand622810c2013-06-28 09:54:59 -07001126 }
1127 break;
Josh Gao9da9ac52016-01-19 14:50:18 -08001128 }
Chris Fries0ea946c2017-04-12 10:25:57 -05001129 case FB_BUFFER_FD:
Tom Cherry9027af02018-09-24 15:48:09 -07001130 fb->FlashPartition(partition, buf->fd, buf->sz);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001131 break;
1132 default:
1133 die("unknown buffer type: %d", buf->type);
1134 }
1135}
1136
Aaron Wisnerdb511202018-06-26 15:38:35 -05001137static std::string get_current_slot() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001138 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07001139 if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
LuK1337dae48ef2020-04-06 14:38:58 +02001140 if (current_slot[0] == '_') current_slot.erase(0, 1);
Elliott Hughes42b18a52018-04-10 15:32:21 -07001141 return current_slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001142}
1143
Aaron Wisnerdb511202018-06-26 15:38:35 -05001144static int get_slot_count() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001145 std::string var;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001146 int count = 0;
Tom Cherry9027af02018-09-24 15:48:09 -07001147 if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
1148 !android::base::ParseInt(var, &count)) {
Elliott Hughes42b18a52018-04-10 15:32:21 -07001149 return 0;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001150 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001151 return count;
1152}
1153
Aaron Wisnerdb511202018-06-26 15:38:35 -05001154static bool supports_AB() {
1155 return get_slot_count() >= 2;
Alex Lightbb9b8a52016-06-29 09:26:44 -07001156}
1157
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001158// Given a current slot, this returns what the 'other' slot is.
Daniel Rosenberg80919472016-06-30 19:25:31 -07001159static std::string get_other_slot(const std::string& current_slot, int count) {
1160 if (count == 0) return "";
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001161
Daniel Rosenberg80919472016-06-30 19:25:31 -07001162 char next = (current_slot[0] - 'a' + 1)%count + 'a';
1163 return std::string(1, next);
1164}
1165
Aaron Wisnerdb511202018-06-26 15:38:35 -05001166static std::string get_other_slot(const std::string& current_slot) {
1167 return get_other_slot(current_slot, get_slot_count());
Daniel Rosenberg80919472016-06-30 19:25:31 -07001168}
1169
Aaron Wisnerdb511202018-06-26 15:38:35 -05001170static std::string get_other_slot(int count) {
1171 return get_other_slot(get_current_slot(), count);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001172}
1173
Aaron Wisnerdb511202018-06-26 15:38:35 -05001174static std::string get_other_slot() {
1175 return get_other_slot(get_current_slot(), get_slot_count());
Alex Lightbb9b8a52016-06-29 09:26:44 -07001176}
1177
Aaron Wisnerdb511202018-06-26 15:38:35 -05001178static std::string verify_slot(const std::string& slot_name, bool allow_all) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001179 std::string slot = slot_name;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001180 if (slot == "all") {
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001181 if (allow_all) {
1182 return "all";
1183 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001184 int count = get_slot_count();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001185 if (count > 0) {
1186 return "a";
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001187 } else {
Elliott Hughes4089d342017-10-27 14:21:12 -07001188 die("No known slots");
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001189 }
1190 }
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001191 }
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001192
Aaron Wisnerdb511202018-06-26 15:38:35 -05001193 int count = get_slot_count();
Elliott Hughes4089d342017-10-27 14:21:12 -07001194 if (count == 0) die("Device does not support slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001195
Daniel Rosenberg80919472016-06-30 19:25:31 -07001196 if (slot == "other") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001197 std::string other = get_other_slot( count);
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001198 if (other == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001199 die("No known slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001200 }
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001201 return other;
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001202 }
1203
Daniel Rosenberg80919472016-06-30 19:25:31 -07001204 if (slot.size() == 1 && (slot[0]-'a' >= 0 && slot[0]-'a' < count)) return slot;
1205
1206 fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
1207 for (int i=0; i<count; i++) {
1208 fprintf(stderr, "%c\n", (char)(i + 'a'));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001209 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001210
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001211 exit(1);
1212}
1213
Aaron Wisnerdb511202018-06-26 15:38:35 -05001214static std::string verify_slot(const std::string& slot) {
1215 return verify_slot(slot, true);
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001216}
1217
Aaron Wisnerdb511202018-06-26 15:38:35 -05001218static void do_for_partition(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001219 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001220 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001221 std::string current_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001222 // |part| can be vendor_boot:default. Append slot to the first token.
1223 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001224
Yifan Hong6d7da632021-02-23 12:15:51 -08001225 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001226 /* If has-slot is not supported, the answer is no. */
1227 has_slot = "no";
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001228 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001229 if (has_slot == "yes") {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001230 if (slot == "") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001231 current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001232 if (current_slot == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001233 die("Failed to identify current slot");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001234 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001235 part_tokens[0] += "_" + current_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001236 } else {
Yifan Hong6d7da632021-02-23 12:15:51 -08001237 part_tokens[0] += "_" + slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001238 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001239 func(android::base::Join(part_tokens, ":"));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001240 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001241 if (force_slot && slot != "") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001242 fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
1243 part_tokens[0].c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001244 }
1245 func(part);
1246 }
1247}
1248
David Pursell0b156632015-10-30 11:22:01 -07001249/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1250 * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1251 * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1252 * partition does not support slots.
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001253 */
Aaron Wisnerdb511202018-06-26 15:38:35 -05001254static void do_for_partitions(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001255 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001256 std::string has_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001257 // |part| can be vendor_boot:default. Query has-slot on the first token only.
1258 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001259
Daniel Rosenberg80919472016-06-30 19:25:31 -07001260 if (slot == "all") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001261 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
1262 die("Could not check if partition %s has slot %s", part_tokens[0].c_str(),
1263 slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001264 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001265 if (has_slot == "yes") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001266 for (int i=0; i < get_slot_count(); i++) {
1267 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001268 }
1269 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001270 do_for_partition(part, "", func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001271 }
1272 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001273 do_for_partition(part, slot, func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001274 }
1275}
1276
David Anderson0c732342018-11-28 17:10:42 -08001277static bool is_retrofit_device() {
1278 std::string value;
1279 if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1280 return false;
1281 }
1282 return android::base::StartsWith(value, "system_");
1283}
1284
Yifan Hongbcd27702021-02-16 19:37:32 -08001285// Fetch a partition from the device to a given fd. This is a wrapper over FetchToFd to fetch
1286// the full image.
1287static uint64_t fetch_partition(const std::string& partition, borrowed_fd fd) {
1288 uint64_t fetch_size = get_uint_var(FB_VAR_MAX_FETCH_SIZE);
1289 if (fetch_size == 0) {
1290 die("Unable to get %s. Device does not support fetch command.", FB_VAR_MAX_FETCH_SIZE);
1291 }
1292 uint64_t partition_size = get_partition_size(partition);
1293 if (partition_size <= 0) {
1294 die("Invalid partition size for partition %s: %" PRId64, partition.c_str(), partition_size);
1295 }
1296
1297 uint64_t offset = 0;
1298 while (offset < partition_size) {
1299 uint64_t chunk_size = std::min(fetch_size, partition_size - offset);
1300 if (fb->FetchToFd(partition, fd, offset, chunk_size) != fastboot::RetCode::SUCCESS) {
1301 die("Unable to fetch %s (offset=%" PRIx64 ", size=%" PRIx64 ")", partition.c_str(),
1302 offset, chunk_size);
1303 }
1304 offset += chunk_size;
1305 }
1306 return partition_size;
1307}
1308
1309static void do_fetch(const std::string& partition, const std::string& slot_override,
1310 const std::string& outfile) {
1311 unique_fd fd(TEMP_FAILURE_RETRY(
1312 open(outfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0644)));
1313 auto fetch = std::bind(fetch_partition, _1, borrowed_fd(fd));
1314 do_for_partitions(partition, slot_override, fetch, false /* force slot */);
1315}
1316
Yifan Honge71fe242021-02-22 15:00:15 -08001317// Return immediately if not flashing a vendor boot image. If flashing a vendor boot image,
1318// repack vendor_boot image with an updated ramdisk. After execution, buf is set
1319// to the new image to flash, and return value is the real partition name to flash.
1320static std::string repack_ramdisk(const char* pname, struct fastboot_buffer* buf) {
1321 std::string_view pname_sv{pname};
1322
1323 if (!android::base::StartsWith(pname_sv, "vendor_boot:") &&
1324 !android::base::StartsWith(pname_sv, "vendor_boot_a:") &&
1325 !android::base::StartsWith(pname_sv, "vendor_boot_b:")) {
1326 return std::string(pname_sv);
1327 }
1328 if (buf->type != FB_BUFFER_FD) {
1329 die("Flashing sparse vendor ramdisk image is not supported.");
1330 }
1331 if (buf->sz <= 0) {
1332 die("repack_ramdisk() sees negative size: %" PRId64, buf->sz);
1333 }
1334 std::string partition(pname_sv.substr(0, pname_sv.find(':')));
1335 std::string ramdisk(pname_sv.substr(pname_sv.find(':') + 1));
1336
1337 unique_fd vendor_boot(make_temporary_fd("vendor boot repack"));
1338 uint64_t vendor_boot_size = fetch_partition(partition, vendor_boot);
1339 auto repack_res = replace_vendor_ramdisk(vendor_boot, vendor_boot_size, ramdisk, buf->fd,
1340 static_cast<uint64_t>(buf->sz));
1341 if (!repack_res.ok()) {
1342 die("%s", repack_res.error().message().c_str());
1343 }
1344
1345 buf->fd = std::move(vendor_boot);
1346 buf->sz = vendor_boot_size;
1347 buf->image_size = vendor_boot_size;
1348 return partition;
1349}
1350
Aaron Wisnerdb511202018-06-26 15:38:35 -05001351static void do_flash(const char* pname, const char* fname) {
Yifan Hong6d7da632021-02-23 12:15:51 -08001352 verbose("Do flash %s %s", pname, fname);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001353 struct fastboot_buffer buf;
1354
Aaron Wisnerdb511202018-06-26 15:38:35 -05001355 if (!load_buf(fname, &buf)) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001356 die("cannot load '%s': %s", fname, strerror(errno));
Rom Lemarchand622810c2013-06-28 09:54:59 -07001357 }
David Anderson629e51c2018-10-25 12:51:25 -07001358 if (is_logical(pname)) {
1359 fb->ResizePartition(pname, std::to_string(buf.image_size));
1360 }
Yifan Honge71fe242021-02-22 15:00:15 -08001361 std::string flash_pname = repack_ramdisk(pname, &buf);
1362 flash_buf(flash_pname, &buf);
Colin Crossf8387882012-05-24 17:18:41 -07001363}
1364
Daniel Rosenberg13454092016-06-27 19:43:11 -07001365// Sets slot_override as the active slot. If slot_override is blank,
1366// set current slot as active instead. This clears slot-unbootable.
Aaron Wisnerdb511202018-06-26 15:38:35 -05001367static void set_active(const std::string& slot_override) {
1368 if (!supports_AB()) return;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001369
Daniel Rosenberg80919472016-06-30 19:25:31 -07001370 if (slot_override != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001371 fb->SetActive(slot_override);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001372 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001373 std::string current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001374 if (current_slot != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001375 fb->SetActive(current_slot);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001376 }
1377 }
1378}
1379
David Anderson32e376f2018-08-16 13:43:11 -07001380static bool is_userspace_fastboot() {
1381 std::string value;
Tom Cherry9027af02018-09-24 15:48:09 -07001382 return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
David Anderson32e376f2018-08-16 13:43:11 -07001383}
1384
David Anderson1d887432018-08-27 16:47:32 -07001385static void reboot_to_userspace_fastboot() {
Tom Cherry9027af02018-09-24 15:48:09 -07001386 fb->RebootTo("fastboot");
1387
1388 auto* old_transport = fb->set_transport(nullptr);
1389 delete old_transport;
David Anderson1d887432018-08-27 16:47:32 -07001390
1391 // Give the current connection time to close.
1392 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
1393
Tom Cherry9027af02018-09-24 15:48:09 -07001394 fb->set_transport(open_device());
David Anderson11d6d272018-12-07 16:39:07 -08001395
1396 if (!is_userspace_fastboot()) {
1397 die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1398 }
Hridya Valsaraju83d856e2019-05-17 14:24:19 -07001399
1400 // Reset target_sparse_limit after reboot to userspace fastboot. Max
1401 // download sizes may differ in bootloader and fastbootd.
1402 target_sparse_limit = -1;
David Anderson1d887432018-08-27 16:47:32 -07001403}
1404
David Andersonab8f4662019-10-21 16:45:59 -07001405static void CancelSnapshotIfNeeded() {
1406 std::string merge_status = "none";
1407 if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
Elliott Hughes6a7ff582020-06-05 14:06:15 -07001408 !merge_status.empty() && merge_status != "none") {
Yifan Hong712c32b2019-12-10 18:11:13 -08001409 fb->SnapshotUpdateCommand("cancel");
David Andersonab8f4662019-10-21 16:45:59 -07001410 }
1411}
1412
David Andersoncf444f32018-08-29 14:15:49 -07001413class ImageSource {
1414 public:
Yifan Hongd2e8cb52021-03-19 11:46:42 -07001415 virtual ~ImageSource() {};
Tom Cherrydfd85df2018-09-20 14:45:05 -07001416 virtual bool ReadFile(const std::string& name, std::vector<char>* out) const = 0;
Yifan Hongb10d0672021-02-22 15:06:27 -08001417 virtual unique_fd OpenFile(const std::string& name) const = 0;
David Andersoncf444f32018-08-29 14:15:49 -07001418};
David Anderson32e376f2018-08-16 13:43:11 -07001419
David Andersoncf444f32018-08-29 14:15:49 -07001420class FlashAllTool {
1421 public:
Andrew Chantd64b9882021-04-06 12:48:27 -07001422 FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary,
1423 bool wipe, bool force_flash);
David Anderson32e376f2018-08-16 13:43:11 -07001424
David Andersoncf444f32018-08-29 14:15:49 -07001425 void Flash();
David Anderson32e376f2018-08-16 13:43:11 -07001426
David Andersoncf444f32018-08-29 14:15:49 -07001427 private:
1428 void CheckRequirements();
1429 void DetermineSecondarySlot();
1430 void CollectImages();
1431 void FlashImages(const std::vector<std::pair<const Image*, std::string>>& images);
1432 void FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf);
1433 void UpdateSuperPartition();
David Anderson32e376f2018-08-16 13:43:11 -07001434
David Andersoncf444f32018-08-29 14:15:49 -07001435 const ImageSource& source_;
1436 std::string slot_override_;
1437 bool skip_secondary_;
1438 bool wipe_;
Andrew Chantd64b9882021-04-06 12:48:27 -07001439 bool force_flash_;
David Andersoncf444f32018-08-29 14:15:49 -07001440 std::string secondary_slot_;
1441 std::vector<std::pair<const Image*, std::string>> boot_images_;
1442 std::vector<std::pair<const Image*, std::string>> os_images_;
1443};
1444
Andrew Chantd64b9882021-04-06 12:48:27 -07001445FlashAllTool::FlashAllTool(const ImageSource& source, const std::string& slot_override,
1446 bool skip_secondary, bool wipe, bool force_flash)
David Andersoncf444f32018-08-29 14:15:49 -07001447 : source_(source),
1448 slot_override_(slot_override),
1449 skip_secondary_(skip_secondary),
Andrew Chantd64b9882021-04-06 12:48:27 -07001450 wipe_(wipe),
1451 force_flash_(force_flash)
David Andersoncf444f32018-08-29 14:15:49 -07001452{
David Anderson32e376f2018-08-16 13:43:11 -07001453}
1454
David Andersoncf444f32018-08-29 14:15:49 -07001455void FlashAllTool::Flash() {
Tom Cherry9027af02018-09-24 15:48:09 -07001456 DumpInfo();
David Andersoncf444f32018-08-29 14:15:49 -07001457 CheckRequirements();
David Anderson96a9fd42018-11-05 15:21:44 -08001458
1459 // Change the slot first, so we boot into the correct recovery image when
1460 // using fastbootd.
1461 if (slot_override_ == "all") {
1462 set_active("a");
1463 } else {
1464 set_active(slot_override_);
1465 }
1466
David Andersoncf444f32018-08-29 14:15:49 -07001467 DetermineSecondarySlot();
1468 CollectImages();
David Anderson32e376f2018-08-16 13:43:11 -07001469
David Andersonab8f4662019-10-21 16:45:59 -07001470 CancelSnapshotIfNeeded();
1471
David Anderson95d40932018-08-28 12:14:33 -07001472 // First flash boot partitions. We allow this to happen either in userspace
1473 // or in bootloader fastboot.
David Andersoncf444f32018-08-29 14:15:49 -07001474 FlashImages(boot_images_);
David Anderson95d40932018-08-28 12:14:33 -07001475
1476 // Sync the super partition. This will reboot to userspace fastboot if needed.
David Andersoncf444f32018-08-29 14:15:49 -07001477 UpdateSuperPartition();
David Anderson95d40932018-08-28 12:14:33 -07001478
1479 // Resize any logical partition to 0, so each partition is reset to 0
1480 // extents, and will achieve more optimal allocation.
David Andersoncf444f32018-08-29 14:15:49 -07001481 for (const auto& [image, slot] : os_images_) {
David Anderson32e376f2018-08-16 13:43:11 -07001482 auto resize_partition = [](const std::string& partition) -> void {
1483 if (is_logical(partition)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001484 fb->ResizePartition(partition, "0");
David Anderson32e376f2018-08-16 13:43:11 -07001485 }
1486 };
David Anderson95d40932018-08-28 12:14:33 -07001487 do_for_partitions(image->part_name, slot, resize_partition, false);
David Anderson32e376f2018-08-16 13:43:11 -07001488 }
1489
David Anderson95d40932018-08-28 12:14:33 -07001490 // Flash OS images, resizing logical partitions as needed.
David Andersoncf444f32018-08-29 14:15:49 -07001491 FlashImages(os_images_);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001492}
1493
David Andersoncf444f32018-08-29 14:15:49 -07001494void FlashAllTool::CheckRequirements() {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001495 std::vector<char> contents;
1496 if (!source_.ReadFile("android-info.txt", &contents)) {
David Andersoncf444f32018-08-29 14:15:49 -07001497 die("could not read android-info.txt");
1498 }
Andrew Chantd64b9882021-04-06 12:48:27 -07001499 ::CheckRequirements({contents.data(), contents.size()}, force_flash_);
David Andersoncf444f32018-08-29 14:15:49 -07001500}
1501
1502void FlashAllTool::DetermineSecondarySlot() {
1503 if (skip_secondary_) {
1504 return;
1505 }
David Anderson96a9fd42018-11-05 15:21:44 -08001506 if (slot_override_ != "" && slot_override_ != "all") {
David Andersoncf444f32018-08-29 14:15:49 -07001507 secondary_slot_ = get_other_slot(slot_override_);
1508 } else {
1509 secondary_slot_ = get_other_slot();
1510 }
1511 if (secondary_slot_ == "") {
1512 if (supports_AB()) {
1513 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1514 }
1515 skip_secondary_ = true;
1516 }
1517}
1518
1519void FlashAllTool::CollectImages() {
1520 for (size_t i = 0; i < arraysize(images); ++i) {
1521 std::string slot = slot_override_;
1522 if (images[i].IsSecondary()) {
1523 if (skip_secondary_) {
1524 continue;
1525 }
1526 slot = secondary_slot_;
1527 }
1528 if (images[i].type == ImageType::BootCritical) {
1529 boot_images_.emplace_back(&images[i], slot);
1530 } else if (images[i].type == ImageType::Normal) {
1531 os_images_.emplace_back(&images[i], slot);
1532 }
1533 }
1534}
1535
1536void FlashAllTool::FlashImages(const std::vector<std::pair<const Image*, std::string>>& images) {
1537 for (const auto& [image, slot] : images) {
1538 fastboot_buffer buf;
Yifan Hongb10d0672021-02-22 15:06:27 -08001539 unique_fd fd = source_.OpenFile(image->img_name);
1540 if (fd < 0 || !load_buf_fd(std::move(fd), &buf)) {
David Andersoncf444f32018-08-29 14:15:49 -07001541 if (image->optional_if_no_image) {
1542 continue;
1543 }
1544 die("could not load '%s': %s", image->img_name, strerror(errno));
1545 }
1546 FlashImage(*image, slot, &buf);
1547 }
1548}
1549
1550void FlashAllTool::FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf) {
1551 auto flash = [&, this](const std::string& partition_name) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001552 std::vector<char> signature_data;
1553 if (source_.ReadFile(image.sig_name, &signature_data)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001554 fb->Download("signature", signature_data);
1555 fb->RawCommand("signature", "installing signature");
David Andersoncf444f32018-08-29 14:15:49 -07001556 }
1557
1558 if (is_logical(partition_name)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001559 fb->ResizePartition(partition_name, std::to_string(buf->image_size));
David Andersoncf444f32018-08-29 14:15:49 -07001560 }
1561 flash_buf(partition_name.c_str(), buf);
1562 };
1563 do_for_partitions(image.part_name, slot, flash, false);
1564}
1565
1566void FlashAllTool::UpdateSuperPartition() {
Yifan Hong58532df2021-03-22 16:39:13 -07001567 unique_fd fd = source_.OpenFile("super_empty.img");
David Andersoncf444f32018-08-29 14:15:49 -07001568 if (fd < 0) {
1569 return;
1570 }
1571 if (!is_userspace_fastboot()) {
1572 reboot_to_userspace_fastboot();
1573 }
David Andersoncf444f32018-08-29 14:15:49 -07001574
David Anderson90fe0a42018-11-05 18:01:32 -08001575 std::string super_name;
1576 if (fb->GetVar("super-partition-name", &super_name) != fastboot::RetCode::SUCCESS) {
1577 super_name = "super";
1578 }
1579 fb->Download(super_name, fd, get_file_size(fd));
1580
1581 std::string command = "update-super:" + super_name;
David Andersoncf444f32018-08-29 14:15:49 -07001582 if (wipe_) {
1583 command += ":wipe";
1584 }
Tom Cherry9027af02018-09-24 15:48:09 -07001585 fb->RawCommand(command, "Updating super partition");
David Anderson0c732342018-11-28 17:10:42 -08001586
1587 // Retrofit devices have two super partitions, named super_a and super_b.
1588 // On these devices, secondary slots must be flashed as physical
1589 // partitions (otherwise they would not mount on first boot). To enforce
1590 // this, we delete any logical partitions for the "other" slot.
1591 if (is_retrofit_device()) {
1592 for (const auto& [image, slot] : os_images_) {
1593 std::string partition_name = image->part_name + "_"s + slot;
1594 if (image->IsSecondary() && is_logical(partition_name)) {
1595 fb->DeletePartition(partition_name);
1596 }
1597 }
1598 }
David Andersoncf444f32018-08-29 14:15:49 -07001599}
1600
1601class ZipImageSource final : public ImageSource {
1602 public:
1603 explicit ZipImageSource(ZipArchiveHandle zip) : zip_(zip) {}
Tom Cherrydfd85df2018-09-20 14:45:05 -07001604 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
Yifan Hongb10d0672021-02-22 15:06:27 -08001605 unique_fd OpenFile(const std::string& name) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001606
1607 private:
1608 ZipArchiveHandle zip_;
1609};
1610
Tom Cherrydfd85df2018-09-20 14:45:05 -07001611bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1612 return UnzipToMemory(zip_, name, out);
David Andersoncf444f32018-08-29 14:15:49 -07001613}
1614
Yifan Hongb10d0672021-02-22 15:06:27 -08001615unique_fd ZipImageSource::OpenFile(const std::string& name) const {
David Andersoncf444f32018-08-29 14:15:49 -07001616 return unzip_to_file(zip_, name.c_str());
1617}
1618
Andrew Chantd64b9882021-04-06 12:48:27 -07001619static void do_update(const char* filename, const std::string& slot_override, bool skip_secondary,
1620 bool force_flash) {
David Andersoncf444f32018-08-29 14:15:49 -07001621 ZipArchiveHandle zip;
1622 int error = OpenArchive(filename, &zip);
1623 if (error != 0) {
1624 die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1625 }
1626
Andrew Chantd64b9882021-04-06 12:48:27 -07001627 FlashAllTool tool(ZipImageSource(zip), slot_override, skip_secondary, false, force_flash);
David Andersoncf444f32018-08-29 14:15:49 -07001628 tool.Flash();
1629
1630 CloseArchive(zip);
1631}
1632
1633class LocalImageSource final : public ImageSource {
1634 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001635 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
Yifan Hongb10d0672021-02-22 15:06:27 -08001636 unique_fd OpenFile(const std::string& name) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001637};
1638
Tom Cherrydfd85df2018-09-20 14:45:05 -07001639bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
David Andersoncf444f32018-08-29 14:15:49 -07001640 auto path = find_item_given_name(name);
1641 if (path.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001642 return false;
David Andersoncf444f32018-08-29 14:15:49 -07001643 }
Tom Cherrydfd85df2018-09-20 14:45:05 -07001644 return ReadFileToVector(path, out);
David Andersoncf444f32018-08-29 14:15:49 -07001645}
1646
Yifan Hongb10d0672021-02-22 15:06:27 -08001647unique_fd LocalImageSource::OpenFile(const std::string& name) const {
David Andersoncf444f32018-08-29 14:15:49 -07001648 auto path = find_item_given_name(name);
Yifan Hongb10d0672021-02-22 15:06:27 -08001649 return unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_BINARY)));
David Andersoncf444f32018-08-29 14:15:49 -07001650}
1651
Andrew Chantd64b9882021-04-06 12:48:27 -07001652static void do_flashall(const std::string& slot_override, bool skip_secondary, bool wipe,
1653 bool force_flash) {
1654 FlashAllTool tool(LocalImageSource(), slot_override, skip_secondary, wipe, force_flash);
David Andersoncf444f32018-08-29 14:15:49 -07001655 tool.Flash();
1656}
1657
Elliott Hughesd6365a72017-05-08 18:04:49 -07001658static std::string next_arg(std::vector<std::string>* args) {
1659 if (args->empty()) syntax_error("expected argument");
1660 std::string result = args->front();
1661 args->erase(args->begin());
1662 return result;
Patrick Tjin51e8b032015-09-01 08:15:23 -07001663}
1664
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001665static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001666 if (args->empty()) syntax_error("empty oem command");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001667
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001668 std::string command(cmd);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001669 while (!args->empty()) {
Elliott Hughes29d5d7d2017-05-11 15:05:13 -07001670 command += " " + next_arg(args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001671 }
Tom Cherry9027af02018-09-24 15:48:09 -07001672 fb->RawCommand(command, "");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001673}
1674
Aaron Wisnerdb511202018-06-26 15:38:35 -05001675static unsigned fb_get_flash_block_size(std::string name) {
Connor O'Brience16a8a2017-02-06 14:39:31 -08001676 std::string sizeString;
Tom Cherry9027af02018-09-24 15:48:09 -07001677 if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001678 // This device does not report flash block sizes, so return 0.
Connor O'Brience16a8a2017-02-06 14:39:31 -08001679 return 0;
1680 }
1681 sizeString = fb_fix_numeric_var(sizeString);
1682
1683 unsigned size;
1684 if (!android::base::ParseUint(sizeString, &size)) {
1685 fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1686 return 0;
1687 }
Connor O'Brien6ef5c242017-11-01 17:37:32 -07001688 if ((size & (size - 1)) != 0) {
1689 fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
Connor O'Brience16a8a2017-02-06 14:39:31 -08001690 return 0;
1691 }
1692 return size;
1693}
1694
Aaron Wisnerdb511202018-06-26 15:38:35 -05001695static void fb_perform_format(
Elliott Hughes5620d222018-03-28 08:20:00 -07001696 const std::string& partition, int skip_if_not_supported,
Elliott Hughesd6365a72017-05-08 18:04:49 -07001697 const std::string& type_override, const std::string& size_override,
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001698 const std::string& initial_dir, const unsigned fs_options) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001699 std::string partition_type, partition_size;
1700
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001701 struct fastboot_buffer buf;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001702 const char* errMsg = nullptr;
1703 const struct fs_generator* gen = nullptr;
Jin Qian4a335822017-04-18 16:23:18 -07001704 TemporaryFile output;
1705 unique_fd fd;
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001706
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001707 unsigned int limit = INT_MAX;
1708 if (target_sparse_limit > 0 && target_sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001709 limit = target_sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001710 }
1711 if (sparse_limit > 0 && sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001712 limit = sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001713 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001714
Tom Cherry9027af02018-09-24 15:48:09 -07001715 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001716 errMsg = "Can't determine partition type.\n";
1717 goto failed;
1718 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001719 if (!type_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001720 if (partition_type != type_override) {
1721 fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001722 partition.c_str(), partition_type.c_str(), type_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001723 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001724 partition_type = type_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001725 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001726
Tom Cherry9027af02018-09-24 15:48:09 -07001727 if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001728 errMsg = "Unable to get partition size\n";
1729 goto failed;
1730 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001731 if (!size_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001732 if (partition_size != size_override) {
1733 fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001734 partition.c_str(), partition_size.c_str(), size_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001735 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001736 partition_size = size_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001737 }
Connor O'Brience16a8a2017-02-06 14:39:31 -08001738 partition_size = fb_fix_numeric_var(partition_size);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001739
Elliott Hughes8ab9a322015-11-02 14:05:57 -08001740 gen = fs_get_generator(partition_type);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001741 if (!gen) {
1742 if (skip_if_not_supported) {
1743 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001744 fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001745 return;
1746 }
Mark Salyzyna30b6962018-11-20 11:04:15 -08001747 die("Formatting is not supported for file system with type '%s'.",
1748 partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001749 }
1750
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001751 int64_t size;
Elliott Hughesda46b392016-10-11 17:09:00 -07001752 if (!android::base::ParseInt(partition_size, &size)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001753 die("Couldn't parse partition size '%s'.", partition_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001754 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001755
Connor O'Brience16a8a2017-02-06 14:39:31 -08001756 unsigned eraseBlkSize, logicalBlkSize;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001757 eraseBlkSize = fb_get_flash_block_size("erase-block-size");
1758 logicalBlkSize = fb_get_flash_block_size("logical-block-size");
Connor O'Brience16a8a2017-02-06 14:39:31 -08001759
Jin Qian4a335822017-04-18 16:23:18 -07001760 if (fs_generator_generate(gen, output.path, size, initial_dir,
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001761 eraseBlkSize, logicalBlkSize, fs_options)) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001762 die("Cannot generate image for %s", partition.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001763 }
1764
Jin Qian4a335822017-04-18 16:23:18 -07001765 fd.reset(open(output.path, O_RDONLY));
1766 if (fd == -1) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001767 die("Cannot open generated image: %s", strerror(errno));
Jin Qian4a335822017-04-18 16:23:18 -07001768 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001769 if (!load_buf_fd(std::move(fd), &buf)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001770 die("Cannot read image: %s", strerror(errno));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001771 }
1772 flash_buf(partition, &buf);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001773 return;
1774
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001775failed:
1776 if (skip_if_not_supported) {
1777 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001778 if (errMsg) fprintf(stderr, "%s", errMsg);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001779 }
Tom Cherry9027af02018-09-24 15:48:09 -07001780 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
Mark Salyzyna30b6962018-11-20 11:04:15 -08001781 if (!skip_if_not_supported) {
1782 die("Command failed");
1783 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001784}
1785
David Anderson89569642018-11-16 15:53:35 -08001786static bool should_flash_in_userspace(const std::string& partition_name) {
David Andersone0e693c2018-11-27 20:19:26 -08001787 if (!get_android_product_out()) {
1788 return false;
1789 }
David Anderson89569642018-11-16 15:53:35 -08001790 auto path = find_item_given_name("super_empty.img");
David Anderson00475802018-12-04 17:05:47 -08001791 if (path.empty() || access(path.c_str(), R_OK)) {
David Anderson89569642018-11-16 15:53:35 -08001792 return false;
1793 }
1794 auto metadata = android::fs_mgr::ReadFromImageFile(path);
1795 if (!metadata) {
1796 return false;
1797 }
1798 for (const auto& partition : metadata->partitions) {
1799 auto candidate = android::fs_mgr::GetPartitionName(partition);
1800 if (partition.attributes & LP_PARTITION_ATTR_SLOT_SUFFIXED) {
1801 // On retrofit devices, we don't know if, or whether, the A or B
1802 // slot has been flashed for dynamic partitions. Instead we add
1803 // both names to the list as a conservative guess.
1804 if (candidate + "_a" == partition_name || candidate + "_b" == partition_name) {
1805 return true;
1806 }
1807 } else if (candidate == partition_name) {
1808 return true;
1809 }
1810 }
1811 return false;
1812}
1813
David Anderson7c84b9f2019-06-27 22:15:29 -07001814static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
1815 std::string* message) {
1816 auto super_device = GetMetadataSuperBlockDevice(metadata);
1817 auto block_size = metadata.geometry.logical_block_size;
1818 auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
1819
1820 if (super_bdev_name != "super") {
1821 // retrofit devices do not allow flashing to the retrofit partitions,
1822 // so enable it if we can.
1823 fb->RawCommand("oem allow-flash-super");
1824 }
1825
1826 // Note: do not use die() in here, since we want TemporaryDir's destructor
1827 // to be called.
1828 TemporaryDir temp_dir;
1829
1830 bool ok;
1831 if (metadata.block_devices.size() > 1) {
1832 ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
1833 } else {
1834 auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
1835 ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
1836 }
1837 if (!ok) {
1838 *message = "Could not generate a flashable super image file";
1839 return false;
1840 }
1841
1842 for (const auto& block_device : metadata.block_devices) {
1843 auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
1844 bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
1845
1846 std::string image_name;
1847 if (metadata.block_devices.size() > 1) {
1848 image_name = "super_" + partition + ".img";
1849 } else {
1850 image_name = partition + ".img";
1851 }
1852
1853 auto image_path = temp_dir.path + "/"s + image_name;
1854 auto flash = [&](const std::string& partition_name) {
1855 do_flash(partition_name.c_str(), image_path.c_str());
1856 };
1857 do_for_partitions(partition, slot, flash, force_slot);
1858
1859 unlink(image_path.c_str());
1860 }
1861 return true;
1862}
1863
1864static void do_wipe_super(const std::string& image, const std::string& slot_override) {
1865 if (access(image.c_str(), R_OK) != 0) {
1866 die("Could not read image: %s", image.c_str());
1867 }
1868 auto metadata = android::fs_mgr::ReadFromImageFile(image);
1869 if (!metadata) {
1870 die("Could not parse image: %s", image.c_str());
1871 }
1872
1873 auto slot = slot_override;
1874 if (slot.empty()) {
1875 slot = get_current_slot();
1876 }
1877
1878 std::string message;
1879 if (!wipe_super(*metadata.get(), slot, &message)) {
1880 die(message);
1881 }
1882}
1883
Aaron Wisnerdb511202018-06-26 15:38:35 -05001884int FastBootTool::Main(int argc, char* argv[]) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001885 bool wants_wipe = false;
1886 bool wants_reboot = false;
1887 bool wants_reboot_bootloader = false;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001888 bool wants_reboot_recovery = false;
1889 bool wants_reboot_fastboot = false;
Mitchell Wills31dce302016-09-26 10:26:21 -07001890 bool skip_reboot = false;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001891 bool wants_set_active = false;
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001892 bool skip_secondary = false;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001893 bool set_fbe_marker = false;
David Anderson89569642018-11-16 15:53:35 -08001894 bool force_flash = false;
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001895 unsigned fs_options = 0;
Florian Bäuerle27ded482014-11-24 11:29:34 +01001896 int longindex;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001897 std::string slot_override;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001898 std::string next_active;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001899
Elliott Hughes577e8b42018-04-05 16:12:47 -07001900 g_boot_img_hdr.kernel_addr = 0x00008000;
1901 g_boot_img_hdr.ramdisk_addr = 0x01000000;
1902 g_boot_img_hdr.second_addr = 0x00f00000;
1903 g_boot_img_hdr.tags_addr = 0x00000100;
1904 g_boot_img_hdr.page_size = 2048;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001905 g_boot_img_hdr.dtb_addr = 0x01100000;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001906
JP Abgrall7b8970c2013-03-07 17:06:41 -08001907 const struct option longopts[] = {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001908 {"base", required_argument, 0, 0},
1909 {"cmdline", required_argument, 0, 0},
1910 {"disable-verification", no_argument, 0, 0},
1911 {"disable-verity", no_argument, 0, 0},
David Anderson89569642018-11-16 15:53:35 -08001912 {"force", no_argument, 0, 0},
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001913 {"fs-options", required_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001914 {"header-version", required_argument, 0, 0},
Elliott Hughes379646b2015-06-02 13:50:00 -07001915 {"help", no_argument, 0, 'h'},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001916 {"kernel-offset", required_argument, 0, 0},
1917 {"os-patch-level", required_argument, 0, 0},
1918 {"os-version", required_argument, 0, 0},
1919 {"page-size", required_argument, 0, 0},
1920 {"ramdisk-offset", required_argument, 0, 0},
Daniel Rosenberg7aa38bc2015-11-11 17:29:37 -08001921 {"set-active", optional_argument, 0, 'a'},
Mitchell Wills31dce302016-09-26 10:26:21 -07001922 {"skip-reboot", no_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001923 {"skip-secondary", no_argument, 0, 0},
1924 {"slot", required_argument, 0, 0},
1925 {"tags-offset", required_argument, 0, 0},
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001926 {"dtb", required_argument, 0, 0},
1927 {"dtb-offset", required_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001928 {"unbuffered", no_argument, 0, 0},
Elliott Hughesf238d872018-03-29 14:46:29 -07001929 {"verbose", no_argument, 0, 'v'},
1930 {"version", no_argument, 0, 0},
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001931#if !defined(_WIN32)
1932 {"wipe-and-use-fbe", no_argument, 0, 0},
1933#endif
JP Abgrall7b8970c2013-03-07 17:06:41 -08001934 {0, 0, 0, 0}
1935 };
Colin Cross8879f982012-05-22 17:53:34 -07001936
1937 serial = getenv("ANDROID_SERIAL");
1938
Elliott Hughes577e8b42018-04-05 16:12:47 -07001939 int c;
Elliott Hughesf3192bd2018-04-10 15:38:08 -07001940 while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001941 if (c == 0) {
1942 std::string name{longopts[longindex].name};
1943 if (name == "base") {
1944 g_base_addr = strtoul(optarg, 0, 16);
1945 } else if (name == "cmdline") {
1946 g_cmdline = optarg;
1947 } else if (name == "disable-verification") {
1948 g_disable_verification = true;
1949 } else if (name == "disable-verity") {
1950 g_disable_verity = true;
David Anderson89569642018-11-16 15:53:35 -08001951 } else if (name == "force") {
1952 force_flash = true;
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001953 } else if (name == "fs-options") {
1954 fs_options = ParseFsOption(optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001955 } else if (name == "header-version") {
1956 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001957 } else if (name == "dtb") {
1958 g_dtb_path = optarg;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001959 } else if (name == "kernel-offset") {
1960 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
1961 } else if (name == "os-patch-level") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001962 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001963 } else if (name == "os-version") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001964 ParseOsVersion(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001965 } else if (name == "page-size") {
1966 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
1967 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
1968 } else if (name == "ramdisk-offset") {
1969 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
1970 } else if (name == "skip-reboot") {
1971 skip_reboot = true;
1972 } else if (name == "skip-secondary") {
1973 skip_secondary = true;
1974 } else if (name == "slot") {
1975 slot_override = optarg;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001976 } else if (name == "dtb-offset") {
1977 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001978 } else if (name == "tags-offset") {
1979 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
1980 } else if (name == "unbuffered") {
Elliott Hughesfc797672015-04-07 20:12:50 -07001981 setvbuf(stdout, nullptr, _IONBF, 0);
1982 setvbuf(stderr, nullptr, _IONBF, 0);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001983 } else if (name == "version") {
Dan Willemsenab971b52018-08-29 14:58:02 -07001984 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION, android::build::GetBuildNumber().c_str());
Elliott Hughes1fd46df2017-03-30 15:08:28 -07001985 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
Elliott Hughes379646b2015-06-02 13:50:00 -07001986 return 0;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001987#if !defined(_WIN32)
Elliott Hughes577e8b42018-04-05 16:12:47 -07001988 } else if (name == "wipe-and-use-fbe") {
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001989 wants_wipe = true;
1990 set_fbe_marker = true;
1991#endif
1992 } else {
Elliott Hughes855cdf82018-04-02 14:24:03 -07001993 die("unknown option %s", longopts[longindex].name);
Florian Bäuerle27ded482014-11-24 11:29:34 +01001994 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07001995 } else {
1996 switch (c) {
1997 case 'a':
1998 wants_set_active = true;
1999 if (optarg) next_active = optarg;
2000 break;
2001 case 'h':
2002 return show_help();
Elliott Hughes577e8b42018-04-05 16:12:47 -07002003 case 'l':
2004 g_long_listing = true;
2005 break;
2006 case 's':
2007 serial = optarg;
2008 break;
2009 case 'S':
Elliott Hughes542370d2018-04-19 19:49:44 -07002010 if (!android::base::ParseByteCount(optarg, &sparse_limit)) {
2011 die("invalid sparse limit %s", optarg);
2012 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07002013 break;
2014 case 'v':
2015 set_verbose();
2016 break;
2017 case 'w':
2018 wants_wipe = true;
2019 break;
2020 case '?':
2021 return 1;
2022 default:
2023 abort();
2024 }
Colin Cross8879f982012-05-22 17:53:34 -07002025 }
2026 }
2027
2028 argc -= optind;
2029 argv += optind;
2030
Elliott Hughesd6365a72017-05-08 18:04:49 -07002031 if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002032
Colin Cross8fb6e062012-07-24 16:36:41 -07002033 if (argc > 0 && !strcmp(*argv, "devices")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002034 list_devices();
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08002035 return 0;
2036 }
2037
Colin Crossc7b75dc2012-08-29 18:17:06 -07002038 if (argc > 0 && !strcmp(*argv, "help")) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002039 return show_help();
Colin Crossc7b75dc2012-08-29 18:17:06 -07002040 }
2041
David Pursell0b156632015-10-30 11:22:01 -07002042 Transport* transport = open_device();
David Pursell2ec418a2016-01-20 08:32:08 -08002043 if (transport == nullptr) {
2044 return 1;
2045 }
Tom Cherry9027af02018-09-24 15:48:09 -07002046 fastboot::DriverCallbacks driver_callbacks = {
2047 .prolog = Status,
2048 .epilog = Epilog,
2049 .info = InfoMessage,
2050 };
2051 fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
2052 fb = &fastboot_driver;
David Pursell2ec418a2016-01-20 08:32:08 -08002053
Elliott Hughes5620d222018-03-28 08:20:00 -07002054 const double start = now();
2055
Aaron Wisnerdb511202018-06-26 15:38:35 -05002056 if (slot_override != "") slot_override = verify_slot(slot_override);
2057 if (next_active != "") next_active = verify_slot(next_active, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002058
2059 if (wants_set_active) {
2060 if (next_active == "") {
2061 if (slot_override == "") {
Daniel Rosenberg13454092016-06-27 19:43:11 -07002062 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07002063 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
LuK1337dae48ef2020-04-06 14:38:58 +02002064 if (current_slot[0] == '_') current_slot.erase(0, 1);
Aaron Wisnerdb511202018-06-26 15:38:35 -05002065 next_active = verify_slot(current_slot, false);
Daniel Rosenberg13454092016-06-27 19:43:11 -07002066 } else {
2067 wants_set_active = false;
2068 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002069 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002070 next_active = verify_slot(slot_override, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002071 }
2072 }
2073 }
Elliott Hughes31dbed72009-10-07 15:38:53 -07002074
Elliott Hughesd6365a72017-05-08 18:04:49 -07002075 std::vector<std::string> args(argv, argv + argc);
2076 while (!args.empty()) {
2077 std::string command = next_arg(&args);
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002078
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002079 if (command == FB_CMD_GETVAR) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002080 std::string variable = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002081 DisplayVarOrError(variable, variable);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002082 } else if (command == FB_CMD_ERASE) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002083 std::string partition = next_arg(&args);
2084 auto erase = [&](const std::string& partition) {
David Pursell0b156632015-10-30 11:22:01 -07002085 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07002086 if (fb->GetVar("partition-type:" + partition, &partition_type) == fastboot::SUCCESS &&
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002087 fs_get_generator(partition_type) != nullptr) {
2088 fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
2089 partition_type.c_str());
2090 }
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002091
Tom Cherry9027af02018-09-24 15:48:09 -07002092 fb->Erase(partition);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002093 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05002094 do_for_partitions(partition, slot_override, erase, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002095 } else if (android::base::StartsWith(command, "format")) {
2096 // Parsing for: "format[:[type][:[size]]]"
2097 // Some valid things:
2098 // - select only the size, and leave default fs type:
2099 // format::0x4000000 userdata
2100 // - default fs type and size:
2101 // format userdata
2102 // format:: userdata
2103 std::vector<std::string> pieces = android::base::Split(command, ":");
2104 std::string type_override;
2105 if (pieces.size() > 1) type_override = pieces[1].c_str();
2106 std::string size_override;
2107 if (pieces.size() > 2) size_override = pieces[2].c_str();
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002108
Elliott Hughesd6365a72017-05-08 18:04:49 -07002109 std::string partition = next_arg(&args);
2110
2111 auto format = [&](const std::string& partition) {
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002112 fb_perform_format(partition, 0, type_override, size_override, "", fs_options);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002113 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07002114 do_for_partitions(partition, slot_override, format, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002115 } else if (command == "signature") {
2116 std::string filename = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002117 std::vector<char> data;
2118 if (!ReadFileToVector(filename, &data)) {
2119 die("could not load '%s': %s", filename.c_str(), strerror(errno));
2120 }
2121 if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
Tom Cherry9027af02018-09-24 15:48:09 -07002122 fb->Download("signature", data);
2123 fb->RawCommand("signature", "installing signature");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002124 } else if (command == FB_CMD_REBOOT) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002125 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002126
2127 if (args.size() == 1) {
2128 std::string what = next_arg(&args);
2129 if (what == "bootloader") {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002130 wants_reboot = false;
2131 wants_reboot_bootloader = true;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002132 } else if (what == "recovery") {
2133 wants_reboot = false;
2134 wants_reboot_recovery = true;
2135 } else if (what == "fastboot") {
2136 wants_reboot = false;
2137 wants_reboot_fastboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002138 } else {
2139 syntax_error("unknown reboot target %s", what.c_str());
Alexey Polyudove0bfb752017-01-03 19:39:13 -08002140 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002141
Elliott Hughesca85df02015-02-25 10:02:00 -08002142 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002143 if (!args.empty()) syntax_error("junk after reboot command");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002144 } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002145 wants_reboot_bootloader = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002146 } else if (command == FB_CMD_REBOOT_RECOVERY) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002147 wants_reboot_recovery = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002148 } else if (command == FB_CMD_REBOOT_FASTBOOT) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002149 wants_reboot_fastboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002150 } else if (command == FB_CMD_CONTINUE) {
Tom Cherry9027af02018-09-24 15:48:09 -07002151 fb->Continue();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002152 } else if (command == FB_CMD_BOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002153 std::string kernel = next_arg(&args);
2154 std::string ramdisk;
2155 if (!args.empty()) ramdisk = next_arg(&args);
2156 std::string second_stage;
2157 if (!args.empty()) second_stage = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002158 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
Tom Cherry9027af02018-09-24 15:48:09 -07002159 fb->Download("boot.img", data);
2160 fb->Boot();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002161 } else if (command == FB_CMD_FLASH) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002162 std::string pname = next_arg(&args);
2163
Elliott Hughes2810d002016-04-25 14:31:18 -07002164 std::string fname;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002165 if (!args.empty()) {
2166 fname = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002167 } else {
Elliott Hughes45964a82017-05-03 22:43:23 -07002168 fname = find_item(pname);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002169 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002170 if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002171
2172 auto flash = [&](const std::string &partition) {
David Anderson89569642018-11-16 15:53:35 -08002173 if (should_flash_in_userspace(partition) && !is_userspace_fastboot() &&
2174 !force_flash) {
2175 die("The partition you are trying to flash is dynamic, and "
2176 "should be flashed via fastbootd. Please run:\n"
2177 "\n"
2178 " fastboot reboot fastboot\n"
2179 "\n"
2180 "And try again. If you are intentionally trying to "
2181 "overwrite a fixed partition, use --force.");
2182 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05002183 do_flash(partition.c_str(), fname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002184 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07002185 do_for_partitions(pname, slot_override, flash, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002186 } else if (command == "flash:raw") {
2187 std::string partition = next_arg(&args);
2188 std::string kernel = next_arg(&args);
2189 std::string ramdisk;
2190 if (!args.empty()) ramdisk = next_arg(&args);
2191 std::string second_stage;
2192 if (!args.empty()) second_stage = next_arg(&args);
2193
Tom Cherrydfd85df2018-09-20 14:45:05 -07002194 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
2195 auto flashraw = [&data](const std::string& partition) {
Tom Cherry9027af02018-09-24 15:48:09 -07002196 fb->FlashPartition(partition, data);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002197 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05002198 do_for_partitions(partition, slot_override, flashraw, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002199 } else if (command == "flashall") {
Alex Lightbb9b8a52016-06-29 09:26:44 -07002200 if (slot_override == "all") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002201 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
Andrew Chantd64b9882021-04-06 12:48:27 -07002202 do_flashall(slot_override, true, wants_wipe, force_flash);
Alex Lightbb9b8a52016-06-29 09:26:44 -07002203 } else {
Andrew Chantd64b9882021-04-06 12:48:27 -07002204 do_flashall(slot_override, skip_secondary, wants_wipe, force_flash);
Alex Lightbb9b8a52016-06-29 09:26:44 -07002205 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002206 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002207 } else if (command == "update") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002208 bool slot_all = (slot_override == "all");
2209 if (slot_all) {
2210 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
2211 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002212 std::string filename = "update.zip";
2213 if (!args.empty()) {
2214 filename = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002215 }
Andrew Chantd64b9882021-04-06 12:48:27 -07002216 do_update(filename.c_str(), slot_override, skip_secondary || slot_all, force_flash);
Mitchell Wills31dce302016-09-26 10:26:21 -07002217 wants_reboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002218 } else if (command == FB_CMD_SET_ACTIVE) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002219 std::string slot = verify_slot(next_arg(&args), false);
Tom Cherry9027af02018-09-24 15:48:09 -07002220 fb->SetActive(slot);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002221 } else if (command == "stage") {
2222 std::string filename = next_arg(&args);
2223
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002224 struct fastboot_buffer buf;
Aaron Wisnerdb511202018-06-26 15:38:35 -05002225 if (!load_buf(filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002226 die("cannot load '%s'", filename.c_str());
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002227 }
Yifan Hong58532df2021-03-22 16:39:13 -07002228 fb->Download(filename, buf.fd.get(), buf.sz);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002229 } else if (command == "get_staged") {
2230 std::string filename = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002231 fb->Upload(filename);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002232 } else if (command == FB_CMD_OEM) {
2233 do_oem_command(FB_CMD_OEM, &args);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002234 } else if (command == "flashing") {
2235 if (args.empty()) {
2236 syntax_error("missing 'flashing' command");
2237 } else if (args.size() == 1 && (args[0] == "unlock" || args[0] == "lock" ||
2238 args[0] == "unlock_critical" ||
2239 args[0] == "lock_critical" ||
Elliott Hughes2e9b7792018-04-04 13:36:44 -07002240 args[0] == "get_unlock_ability")) {
Elliott Hughes1eec97a2017-05-15 16:53:53 -07002241 do_oem_command("flashing", &args);
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002242 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002243 syntax_error("unknown 'flashing' command %s", args[0].c_str());
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002244 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002245 } else if (command == FB_CMD_CREATE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002246 std::string partition = next_arg(&args);
2247 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002248 fb->CreatePartition(partition, size);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002249 } else if (command == FB_CMD_DELETE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002250 std::string partition = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002251 fb->DeletePartition(partition);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002252 } else if (command == FB_CMD_RESIZE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002253 std::string partition = next_arg(&args);
2254 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002255 fb->ResizePartition(partition, size);
David Anderson1d504e32019-01-15 14:38:20 -08002256 } else if (command == "gsi") {
David Anderson3d782d52019-01-29 13:09:49 -08002257 std::string arg = next_arg(&args);
2258 if (arg == "wipe") {
David Anderson1d504e32019-01-15 14:38:20 -08002259 fb->RawCommand("gsi:wipe", "wiping GSI");
David Anderson3d782d52019-01-29 13:09:49 -08002260 } else if (arg == "disable") {
David Anderson1d504e32019-01-15 14:38:20 -08002261 fb->RawCommand("gsi:disable", "disabling GSI");
2262 } else {
2263 syntax_error("expected 'wipe' or 'disable'");
2264 }
David Anderson7c84b9f2019-06-27 22:15:29 -07002265 } else if (command == "wipe-super") {
2266 std::string image;
2267 if (args.empty()) {
2268 image = find_item_given_name("super_empty.img");
2269 } else {
2270 image = next_arg(&args);
2271 }
2272 do_wipe_super(image, slot_override);
David Andersonab8f4662019-10-21 16:45:59 -07002273 } else if (command == "snapshot-update") {
2274 std::string arg;
2275 if (!args.empty()) {
2276 arg = next_arg(&args);
2277 }
David Anderson220ddb12019-10-31 18:02:41 -07002278 if (!arg.empty() && (arg != "cancel" && arg != "merge")) {
2279 syntax_error("expected: snapshot-update [cancel|merge]");
David Andersonab8f4662019-10-21 16:45:59 -07002280 }
2281 fb->SnapshotUpdateCommand(arg);
Yifan Hongbcd27702021-02-16 19:37:32 -08002282 } else if (command == FB_CMD_FETCH) {
2283 std::string partition = next_arg(&args);
2284 std::string outfile = next_arg(&args);
2285 do_fetch(partition, slot_override, outfile);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002286 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002287 syntax_error("unknown command %s", command.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002288 }
2289 }
2290
2291 if (wants_wipe) {
David Andersonab8f4662019-10-21 16:45:59 -07002292 if (force_flash) {
2293 CancelSnapshotIfNeeded();
2294 }
Paul Crowley4d170062018-04-24 17:06:30 -07002295 std::vector<std::string> partitions = { "userdata", "cache", "metadata" };
2296 for (const auto& partition : partitions) {
2297 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07002298 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
2299 continue;
2300 }
Paul Crowley4d170062018-04-24 17:06:30 -07002301 if (partition_type.empty()) continue;
Tom Cherry9027af02018-09-24 15:48:09 -07002302 fb->Erase(partition);
Paul Crowley4d170062018-04-24 17:06:30 -07002303 if (partition == "userdata" && set_fbe_marker) {
2304 fprintf(stderr, "setting FBE marker on initial userdata...\n");
2305 std::string initial_userdata_dir = create_fbemarker_tmpdir();
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002306 fb_perform_format(partition, 1, partition_type, "", initial_userdata_dir, fs_options);
Paul Crowley4d170062018-04-24 17:06:30 -07002307 delete_fbemarker_tmpdir(initial_userdata_dir);
2308 } else {
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002309 fb_perform_format(partition, 1, partition_type, "", "", fs_options);
Paul Crowley4d170062018-04-24 17:06:30 -07002310 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002311 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002312 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002313 if (wants_set_active) {
Tom Cherry9027af02018-09-24 15:48:09 -07002314 fb->SetActive(next_active);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002315 }
Mitchell Wills31dce302016-09-26 10:26:21 -07002316 if (wants_reboot && !skip_reboot) {
Tom Cherry9027af02018-09-24 15:48:09 -07002317 fb->Reboot();
2318 fb->WaitForDisconnect();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002319 } else if (wants_reboot_bootloader) {
Tom Cherry9027af02018-09-24 15:48:09 -07002320 fb->RebootTo("bootloader");
2321 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002322 } else if (wants_reboot_recovery) {
Tom Cherry9027af02018-09-24 15:48:09 -07002323 fb->RebootTo("recovery");
2324 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002325 } else if (wants_reboot_fastboot) {
David Anderson11d6d272018-12-07 16:39:07 -08002326 reboot_to_userspace_fastboot();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002327 }
2328
Elliott Hughes5620d222018-03-28 08:20:00 -07002329 fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
David Anderson03de6452018-09-04 14:32:54 -07002330
Tom Cherry9027af02018-09-24 15:48:09 -07002331 auto* old_transport = fb->set_transport(nullptr);
2332 delete old_transport;
2333
Tom Cherry11f12092018-08-29 21:36:28 -07002334 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002335}
Elliott Hughes6ebec932018-04-10 14:22:13 -07002336
Aaron Wisnerdb511202018-06-26 15:38:35 -05002337void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002338 unsigned year, month, day;
2339 if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2340 syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2341 }
2342 if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2343 if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2344 hdr->SetOsPatchLevel(year, month);
2345}
2346
Aaron Wisnerdb511202018-06-26 15:38:35 -05002347void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002348 unsigned major = 0, minor = 0, patch = 0;
2349 std::vector<std::string> versions = android::base::Split(arg, ".");
2350 if (versions.size() < 1 || versions.size() > 3 ||
2351 (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2352 (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2353 (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2354 (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2355 syntax_error("bad OS version: %s", arg);
2356 }
2357 hdr->SetOsVersion(major, minor, patch);
2358}
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002359
2360unsigned FastBootTool::ParseFsOption(const char* arg) {
2361 unsigned fsOptions = 0;
2362
2363 std::vector<std::string> options = android::base::Split(arg, ",");
2364 if (options.size() < 1)
2365 syntax_error("bad options: %s", arg);
2366
2367 for (size_t i = 0; i < options.size(); ++i) {
2368 if (options[i] == "casefold")
2369 fsOptions |= (1 << FS_OPT_CASEFOLD);
2370 else if (options[i] == "projid")
2371 fsOptions |= (1 << FS_OPT_PROJID);
2372 else if (options[i] == "compress")
2373 fsOptions |= (1 << FS_OPT_COMPRESS);
2374 else
2375 syntax_error("unsupported options: %s", options[i].c_str());
2376 }
2377 return fsOptions;
2378}