blob: 1ce4e8b2b5c6e3065692f16145cb0c782b87d89b [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 Zheng0d307182023-01-31 21:07:53 +000047#include <fstream>
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -070048#include <functional>
Daniel Zheng0d307182023-01-31 21:07:53 +000049#include <iostream>
50#include <memory>
Tom Cherry4aa60b32018-09-05 15:11:44 -070051#include <regex>
Daniel Zheng0d307182023-01-31 21:07:53 +000052#include <sstream>
David Anderson0c732342018-11-28 17:10:42 -080053#include <string>
Elliott Hughes290a2282016-11-14 17:08:47 -080054#include <thread>
Josh Gao9da9ac52016-01-19 14:50:18 -080055#include <utility>
56#include <vector>
Colin Crossf8387882012-05-24 17:18:41 -070057
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080058#include <android-base/endian.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070059#include <android-base/file.h>
David Andersona67fc322023-01-27 16:15:52 -080060#include <android-base/logging.h>
Elliott Hughes749ae2d2016-06-28 14:48:45 -070061#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080062#include <android-base/parseint.h>
David Pursell2ec418a2016-01-20 08:32:08 -080063#include <android-base/parsenetaddress.h>
Elliott Hughes2810d002016-04-25 14:31:18 -070064#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080065#include <android-base/strings.h>
Chris Fries0ea946c2017-04-12 10:25:57 -050066#include <android-base/unique_fd.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070067#include <build/version.h>
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080068#include <libavb/libavb.h>
David Anderson89569642018-11-16 15:53:35 -080069#include <liblp/liblp.h>
David Anderson667b1ef2023-01-27 21:11:11 -080070#include <liblp/super_layout_builder.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070071#include <platform_tools_version.h>
Colin Crossf8387882012-05-24 17:18:41 -070072#include <sparse/sparse.h>
Elliott Hughesd30ad8a2015-03-18 23:12:44 -070073#include <ziparchive/zip_archive.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080074
Elliott Hughes253c18d2015-03-18 22:47:09 -070075#include "bootimg_utils.h"
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -070076#include "constants.h"
Elliott Hughes1b708d32015-12-11 19:07:01 -080077#include "diagnose_usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070078#include "fastboot_driver.h"
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -070079#include "fs.h"
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +000080#include "storage.h"
David Anderson667b1ef2023-01-27 21:11:11 -080081#include "super_flash_helper.h"
Daniel Zheng1a01a1c2023-01-30 23:29:50 +000082#include "task.h"
David Pursell2ec418a2016-01-20 08:32:08 -080083#include "tcp.h"
David Pursell0b156632015-10-30 11:22:01 -070084#include "transport.h"
David Pursell4601c972016-02-05 15:35:09 -080085#include "udp.h"
David Pursell0b156632015-10-30 11:22:01 -070086#include "usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070087#include "util.h"
Yifan Honge71fe242021-02-22 15:00:15 -080088#include "vendor_boot_img_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080089
Yifan Hongbcd27702021-02-16 19:37:32 -080090using android::base::borrowed_fd;
Tom Cherrydfd85df2018-09-20 14:45:05 -070091using android::base::ReadFully;
Tom Cherry4aa60b32018-09-05 15:11:44 -070092using android::base::Split;
93using android::base::Trim;
Chris Fries0ea946c2017-04-12 10:25:57 -050094using android::base::unique_fd;
David Anderson0c732342018-11-28 17:10:42 -080095using namespace std::string_literals;
Yifan Hongbcd27702021-02-16 19:37:32 -080096using namespace std::placeholders;
Chris Fries0ea946c2017-04-12 10:25:57 -050097
Daniel Zheng451e46f2023-04-28 16:37:46 -070098#define FASTBOOT_INFO_VERSION 1
99
David Pursell2ec418a2016-01-20 08:32:08 -0800100static const char* serial = nullptr;
Elliott Hughes577e8b42018-04-05 16:12:47 -0700101
Elliott Hughes577e8b42018-04-05 16:12:47 -0700102static bool g_long_listing = false;
Chris Fries6a999712017-04-04 09:52:47 -0500103// Don't resparse files in too-big chunks.
104// libsparse will support INT_MAX, but this results in large allocations, so
105// let's keep it at 1GB to avoid memory pressure on the host.
106static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
Colin Crossf8387882012-05-24 17:18:41 -0700107static int64_t target_sparse_limit = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800108
Elliott Hughes577e8b42018-04-05 16:12:47 -0700109static unsigned g_base_addr = 0x10000000;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800110static boot_img_hdr_v2 g_boot_img_hdr = {};
Elliott Hughes577e8b42018-04-05 16:12:47 -0700111static std::string g_cmdline;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800112static std::string g_dtb_path;
JP Abgrall7b8970c2013-03-07 17:06:41 -0800113
David Zeuthenb6ea4352017-08-07 14:29:26 -0400114static bool g_disable_verity = false;
115static bool g_disable_verification = false;
116
Tom Cherry9027af02018-09-24 15:48:09 -0700117fastboot::FastBootDriver* fb = nullptr;
118
Daniel Zheng65452d02022-11-30 02:25:31 +0000119static std::vector<Image> images = {
Dario Frenic7ea1af2018-05-25 16:07:19 +0100120 // clang-format off
David Anderson0debda02018-08-28 13:54:03 -0700121 { "boot", "boot.img", "boot.sig", "boot", false, ImageType::BootCritical },
Paul Lawrence556c46b2023-07-17 13:41:38 -0700122 { "bootloader",
123 "bootloader.img", "", "bootloader",
124 true, ImageType::Extra },
Devin Mooredd1eb872022-01-05 00:20:15 +0000125 { "init_boot",
126 "init_boot.img", "init_boot.sig",
127 "init_boot",
Devin Moore60bd33f2022-01-11 02:01:26 +0000128 true, ImageType::BootCritical },
Daniel Zheng65452d02022-11-30 02:25:31 +0000129 { "", "boot_other.img", "boot.sig", "boot", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700130 { "cache", "cache.img", "cache.sig", "cache", true, ImageType::Extra },
131 { "dtbo", "dtbo.img", "dtbo.sig", "dtbo", true, ImageType::BootCritical },
132 { "dts", "dt.img", "dt.sig", "dts", true, ImageType::BootCritical },
133 { "odm", "odm.img", "odm.sig", "odm", true, ImageType::Normal },
Yifan Hongbe78bb62020-07-15 17:07:11 -0700134 { "odm_dlkm", "odm_dlkm.img", "odm_dlkm.sig", "odm_dlkm", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700135 { "product", "product.img", "product.sig", "product", true, ImageType::Normal },
Andrew Scullbe823d72021-01-15 14:37:15 +0000136 { "pvmfw", "pvmfw.img", "pvmfw.sig", "pvmfw", true, ImageType::BootCritical },
Paul Lawrence556c46b2023-07-17 13:41:38 -0700137 { "radio", "radio.img", "", "radio", true, ImageType::Extra },
David Anderson0debda02018-08-28 13:54:03 -0700138 { "recovery", "recovery.img", "recovery.sig", "recovery", true, ImageType::BootCritical },
139 { "super", "super.img", "super.sig", "super", true, ImageType::Extra },
140 { "system", "system.img", "system.sig", "system", false, ImageType::Normal },
Ramji Jiyanib3ddb532021-12-06 02:28:28 +0000141 { "system_dlkm",
142 "system_dlkm.img", "system_dlkm.sig",
143 "system_dlkm",
144 true, ImageType::Normal },
Justin Yun5d0ac622019-06-26 09:18:03 +0900145 { "system_ext",
146 "system_ext.img", "system_ext.sig",
147 "system_ext",
148 true, ImageType::Normal },
Daniel Zheng65452d02022-11-30 02:25:31 +0000149 { "", "system_other.img", "system.sig", "system", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700150 { "userdata", "userdata.img", "userdata.sig", "userdata", true, ImageType::Extra },
151 { "vbmeta", "vbmeta.img", "vbmeta.sig", "vbmeta", true, ImageType::BootCritical },
David Anderson166bfef2018-10-15 14:46:59 -0700152 { "vbmeta_system",
153 "vbmeta_system.img",
154 "vbmeta_system.sig",
155 "vbmeta_system",
David Anderson1109c922018-09-17 17:32:54 -0700156 true, ImageType::BootCritical },
Bowgo Tsaia48a7832021-06-03 14:39:34 +0800157 { "vbmeta_vendor",
158 "vbmeta_vendor.img",
159 "vbmeta_vendor.sig",
160 "vbmeta_vendor",
161 true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700162 { "vendor", "vendor.img", "vendor.sig", "vendor", true, ImageType::Normal },
Steve Muckle36112432019-08-21 11:16:14 -0700163 { "vendor_boot",
164 "vendor_boot.img", "vendor_boot.sig",
165 "vendor_boot",
166 true, ImageType::BootCritical },
Yifan Hong6b1c15c2020-05-12 10:38:53 -0700167 { "vendor_dlkm",
168 "vendor_dlkm.img", "vendor_dlkm.sig",
169 "vendor_dlkm",
170 true, ImageType::Normal },
Lucas Weif0fb5dd2022-03-28 21:57:58 +0800171 { "vendor_kernel_boot",
172 "vendor_kernel_boot.img",
173 "vendor_kernel_boot.sig",
174 "vendor_kernel_boot",
175 true, ImageType::BootCritical },
Daniel Zheng65452d02022-11-30 02:25:31 +0000176 { "", "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
Dario Frenic7ea1af2018-05-25 16:07:19 +0100177 // clang-format on
Rom Lemarchand622810c2013-06-28 09:54:59 -0700178};
Brian Swetland2a63bb72009-04-28 16:05:07 -0700179
David Andersone0e693c2018-11-27 20:19:26 -0800180static char* get_android_product_out() {
Elliott Hughes45964a82017-05-03 22:43:23 -0700181 char* dir = getenv("ANDROID_PRODUCT_OUT");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700182 if (dir == nullptr || dir[0] == '\0') {
David Andersone0e693c2018-11-27 20:19:26 -0800183 return nullptr;
184 }
185 return dir;
186}
187
188static std::string find_item_given_name(const std::string& img_name) {
189 char* dir = get_android_product_out();
190 if (!dir) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700191 die("ANDROID_PRODUCT_OUT not set");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700192 }
David Anderson0debda02018-08-28 13:54:03 -0700193 return std::string(dir) + "/" + img_name;
Alex Lightbb9b8a52016-06-29 09:26:44 -0700194}
195
Daniel Zheng0d307182023-01-31 21:07:53 +0000196std::string find_item(const std::string& item) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000197 for (size_t i = 0; i < images.size(); ++i) {
198 if (!images[i].nickname.empty() && item == images[i].nickname) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700199 return find_item_given_name(images[i].img_name);
200 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201 }
202
Elliott Hughesd6365a72017-05-08 18:04:49 -0700203 fprintf(stderr, "unknown partition '%s'\n", item.c_str());
Elliott Hughes45964a82017-05-03 22:43:23 -0700204 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800205}
206
Tom Cherry9027af02018-09-24 15:48:09 -0700207double last_start_time;
208
209static void Status(const std::string& message) {
Tom Cherry2217c502020-06-10 09:29:25 -0700210 if (!message.empty()) {
211 static constexpr char kStatusFormat[] = "%-50s ";
212 fprintf(stderr, kStatusFormat, message.c_str());
213 }
Tom Cherry9027af02018-09-24 15:48:09 -0700214 last_start_time = now();
215}
216
217static void Epilog(int status) {
218 if (status) {
219 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
220 die("Command failed");
221 } else {
222 double split = now();
223 fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
224 }
225}
226
227static void InfoMessage(const std::string& info) {
228 fprintf(stderr, "(bootloader) %s\n", info.c_str());
229}
230
Raphael Herouart99097cc2022-12-30 11:51:54 +0000231static void TextMessage(const std::string& text) {
232 fprintf(stderr, "%s", text.c_str());
233}
234
Tom Cherrydfd85df2018-09-20 14:45:05 -0700235bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
236 out->clear();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800237
Tom Cherrydfd85df2018-09-20 14:45:05 -0700238 unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
239 if (fd == -1) {
240 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700241 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242
Tom Cherrydfd85df2018-09-20 14:45:05 -0700243 out->resize(get_file_size(fd));
244 return ReadFully(fd, out->data(), out->size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700245}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800246
Elliott Hughesfc797672015-04-07 20:12:50 -0700247static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
Elliott Hughese1746fd2015-08-10 15:30:54 -0700248 if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
249 return -1;
250 }
251
Scott Anderson13081c62012-04-06 12:39:30 -0700252 // require matching serial number or device path if requested
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800253 // at the command line with the -s option.
JP Abgralla032ded2012-06-06 11:53:33 -0700254 if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
Daniel Zheng65452d02022-11-30 02:25:31 +0000255 strcmp(local_serial, info->device_path) != 0))
256 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257 return 0;
258}
259
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000260static ifc_match_func match_fastboot(const char* local_serial = serial) {
261 return [local_serial](usb_ifc_info* info) -> int {
262 return match_fastboot_with_serial(info, local_serial);
263 };
264}
265
266// output compatible with "adb devices"
267static void PrintDevice(const char* local_serial, const char* status = nullptr,
268 const char* details = nullptr) {
269 if (local_serial == nullptr || strlen(local_serial) == 0) {
270 return;
271 }
272
273 if (g_long_listing) {
274 printf("%-22s", local_serial);
275 } else {
276 printf("%s\t", local_serial);
277 }
278
279 if (status != nullptr && strlen(status) > 0) {
280 printf(" %s", status);
281 }
282
283 if (g_long_listing) {
284 if (details != nullptr && strlen(details) > 0) {
285 printf(" %s", details);
286 }
287 }
288
289 putchar('\n');
JP Abgrall7b8970c2013-03-07 17:06:41 -0800290}
291
Elliott Hughesfc797672015-04-07 20:12:50 -0700292static int list_devices_callback(usb_ifc_info* info) {
293 if (match_fastboot_with_serial(info, nullptr) == 0) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800294 std::string serial = info->serial_number;
David Anderson4e058ca2020-05-28 04:39:37 +0000295 std::string interface = info->interface;
296 if (interface.empty()) {
297 interface = "fastboot";
298 }
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700299 if (!info->writable) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800300 serial = UsbNoPermissionsShortHelpText();
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700301 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800302 if (!serial[0]) {
303 serial = "????????????";
304 }
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000305
306 PrintDevice(serial.c_str(), interface.c_str(), info->device_path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800307 }
308
309 return -1;
310}
311
Dmitrii Merkurevcdbfa7a2023-03-01 23:50:05 +0000312Result<NetworkSerial, FastbootError> ParseNetworkSerial(const std::string& serial) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000313 Socket::Protocol protocol;
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000314 const char* net_address = nullptr;
315 int port = 0;
316
317 if (android::base::StartsWith(serial, "tcp:")) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000318 protocol = Socket::Protocol::kTcp;
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000319 net_address = serial.c_str() + strlen("tcp:");
320 port = tcp::kDefaultPort;
321 } else if (android::base::StartsWith(serial, "udp:")) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000322 protocol = Socket::Protocol::kUdp;
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000323 net_address = serial.c_str() + strlen("udp:");
324 port = udp::kDefaultPort;
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000325 } else {
Dmitrii Merkurevcdbfa7a2023-03-01 23:50:05 +0000326 return Error<FastbootError>(FastbootError::Type::NETWORK_SERIAL_WRONG_PREFIX)
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000327 << "protocol prefix ('tcp:' or 'udp:') is missed: " << serial << ". "
328 << "Expected address format:\n"
329 << "<protocol>:<address>:<port> (tcp:localhost:5554)";
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000330 }
331
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000332 std::string error;
333 std::string host;
334 if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
Dmitrii Merkurevcdbfa7a2023-03-01 23:50:05 +0000335 return Error<FastbootError>(FastbootError::Type::NETWORK_SERIAL_WRONG_ADDRESS)
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000336 << "invalid network address '" << net_address << "': " << error;
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000337 }
338
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000339 return NetworkSerial{protocol, host, port};
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000340}
341
342// Opens a new Transport connected to the particular device.
343// arguments:
David Pursell2ec418a2016-01-20 08:32:08 -0800344//
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000345// local_serial - device to connect (can be a network or usb serial name)
346// wait_for_device - flag indicates whether we need to wait for device
347// announce - flag indicates whether we need to print error to stdout in case
348// we cannot connect to the device
David Pursell2ec418a2016-01-20 08:32:08 -0800349//
350// The returned Transport is a singleton, so multiple calls to this function will return the same
351// object, and the caller should not attempt to delete the returned Transport.
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000352static Transport* open_device(const char* local_serial, bool wait_for_device = true,
353 bool announce = true) {
Dmitrii Merkurevcdbfa7a2023-03-01 23:50:05 +0000354 const Result<NetworkSerial, FastbootError> network_serial = ParseNetworkSerial(local_serial);
David Pursell2ec418a2016-01-20 08:32:08 -0800355
David Anderson1d887432018-08-27 16:47:32 -0700356 Transport* transport = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800357 while (true) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000358 if (network_serial.ok()) {
David Pursell2ec418a2016-01-20 08:32:08 -0800359 std::string error;
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000360 if (network_serial->protocol == Socket::Protocol::kTcp) {
361 transport = tcp::Connect(network_serial->address, network_serial->port, &error)
362 .release();
363 } else if (network_serial->protocol == Socket::Protocol::kUdp) {
364 transport = udp::Connect(network_serial->address, network_serial->port, &error)
365 .release();
David Pursell4601c972016-02-05 15:35:09 -0800366 }
367
David Pursell2ec418a2016-01-20 08:32:08 -0800368 if (transport == nullptr && announce) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000369 LOG(ERROR) << "error: " << error;
David Pursell2ec418a2016-01-20 08:32:08 -0800370 }
Dmitrii Merkurevcdbfa7a2023-03-01 23:50:05 +0000371 } else if (network_serial.error().code() ==
372 FastbootError::Type::NETWORK_SERIAL_WRONG_PREFIX) {
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000373 // WRONG_PREFIX is special because it happens when user wants to communicate with USB
374 // device
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000375 transport = usb_open(match_fastboot(local_serial));
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000376 } else {
377 Expect(network_serial);
David Pursell2ec418a2016-01-20 08:32:08 -0800378 }
379
380 if (transport != nullptr) {
381 return transport;
382 }
383
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000384 if (!wait_for_device) {
385 return nullptr;
386 }
387
David Pursell0b156632015-10-30 11:22:01 -0700388 if (announce) {
David Pursell2ec418a2016-01-20 08:32:08 -0800389 announce = false;
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000390 LOG(ERROR) << "< waiting for " << local_serial << ">";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391 }
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000392 std::this_thread::sleep_for(std::chrono::seconds(1));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393 }
394}
395
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000396static Transport* NetworkDeviceConnected(bool print = false) {
397 Transport* transport = nullptr;
398 Transport* result = nullptr;
399
400 ConnectedDevicesStorage storage;
401 std::set<std::string> devices;
Dmitrii Merkurev6c008ff2023-06-02 12:44:31 +0100402 if (storage.Exists()) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000403 FileLock lock = storage.Lock();
404 devices = storage.ReadDevices(lock);
405 }
406
407 for (const std::string& device : devices) {
408 transport = open_device(device.c_str(), false, false);
409
410 if (print) {
Dmitrii Merkurevc48cd9f2023-02-15 15:34:58 +0000411 PrintDevice(device.c_str(), transport == nullptr ? "offline" : "fastboot");
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000412 }
413
414 if (transport != nullptr) {
415 result = transport;
416 }
417 }
418
419 return result;
420}
421
422// Detects the fastboot connected device to open a new Transport.
423// Detecting logic:
424//
425// if serial is provided - try to connect to this particular usb/network device
426// othervise:
427// 1. Check connected usb devices and return the last connected one
428// 2. Check connected network devices and return the last connected one
429// 2. If nothing is connected - wait for any device by repeating p. 1 and 2
430//
431// The returned Transport is a singleton, so multiple calls to this function will return the same
432// object, and the caller should not attempt to delete the returned Transport.
433static Transport* open_device() {
434 if (serial != nullptr) {
435 return open_device(serial);
436 }
437
438 bool announce = true;
439 Transport* transport = nullptr;
440 while (true) {
441 transport = usb_open(match_fastboot(nullptr));
442 if (transport != nullptr) {
443 return transport;
444 }
445
446 transport = NetworkDeviceConnected();
447 if (transport != nullptr) {
448 return transport;
449 }
450
451 if (announce) {
452 announce = false;
453 LOG(ERROR) << "< waiting for any device >";
454 }
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000455 std::this_thread::sleep_for(std::chrono::seconds(1));
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000456 }
457}
458
459static int Connect(int argc, char* argv[]) {
460 if (argc != 1) {
461 LOG(FATAL) << "connect command requires to receive only 1 argument. Usage:" << std::endl
462 << "fastboot connect [tcp:|udp:host:port]";
463 }
464
465 const char* local_serial = *argv;
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000466 Expect(ParseNetworkSerial(local_serial));
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000467
468 const Transport* transport = open_device(local_serial, false);
469 if (transport == nullptr) {
470 return 1;
471 }
472
473 ConnectedDevicesStorage storage;
474 {
475 FileLock lock = storage.Lock();
476 std::set<std::string> devices = storage.ReadDevices(lock);
477 devices.insert(local_serial);
478 storage.WriteDevices(lock, devices);
479 }
480
481 return 0;
482}
483
484static int Disconnect(const char* local_serial) {
Dmitrii Merkurev47855542023-02-28 21:02:48 +0000485 Expect(ParseNetworkSerial(local_serial));
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000486
487 ConnectedDevicesStorage storage;
488 {
489 FileLock lock = storage.Lock();
490 std::set<std::string> devices = storage.ReadDevices(lock);
491 devices.erase(local_serial);
492 storage.WriteDevices(lock, devices);
493 }
494
495 return 0;
496}
497
498static int Disconnect() {
499 ConnectedDevicesStorage storage;
500 {
501 FileLock lock = storage.Lock();
502 storage.Clear(lock);
503 }
504
505 return 0;
506}
507
508static int Disconnect(int argc, char* argv[]) {
509 switch (argc) {
510 case 0: {
511 return Disconnect();
512 }
513 case 1: {
514 return Disconnect(*argv);
515 }
516 default:
517 LOG(FATAL) << "disconnect command can receive only 0 or 1 arguments. Usage:"
518 << std::endl
519 << "fastboot disconnect # disconnect all devices" << std::endl
520 << "fastboot disconnect [tcp:|udp:host:port] # disconnect device";
521 }
522
523 return 0;
524}
525
Elliott Hughesfc797672015-04-07 20:12:50 -0700526static void list_devices() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527 // We don't actually open a USB device here,
528 // just getting our callback called so we can
529 // list all the connected devices.
530 usb_open(list_devices_callback);
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +0000531 NetworkDeviceConnected(/* print */ true);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532}
Daniel Zheng0d307182023-01-31 21:07:53 +0000533void syntax_error(const char* fmt, ...) {
Elliott Hughesd6365a72017-05-08 18:04:49 -0700534 fprintf(stderr, "fastboot: usage: ");
535
536 va_list ap;
537 va_start(ap, fmt);
538 vfprintf(stderr, fmt, ap);
539 va_end(ap);
540
541 fprintf(stderr, "\n");
542 exit(1);
543}
544
545static int show_help() {
546 // clang-format off
547 fprintf(stdout,
Elliott Hughes07fc6822018-05-24 16:36:05 -0700548// 1 2 3 4 5 6 7 8
549// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
Elliott Hughesb76188f2018-04-03 13:30:18 -0700550 "usage: fastboot [OPTION...] COMMAND...\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551 "\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700552 "flashing:\n"
553 " update ZIP Flash all partitions from an update.zip package.\n"
554 " flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
555 " On A/B devices, flashed slot is set as active.\n"
556 " Secondary images may be flashed to inactive slot.\n"
Elliott Hughes07fc6822018-05-24 16:36:05 -0700557 " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
558 " $ANDROID_PRODUCT_OUT if no filename is given.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700559 "\n"
560 "basics:\n"
561 " devices [-l] List devices in bootloader (-l: with device paths).\n"
562 " getvar NAME Display given bootloader variable.\n"
563 " reboot [bootloader] Reboot device.\n"
564 "\n"
565 "locking/unlocking:\n"
566 " flashing lock|unlock Lock/unlock partitions for flashing\n"
567 " flashing lock_critical|unlock_critical\n"
568 " Lock/unlock 'critical' bootloader partitions.\n"
569 " flashing get_unlock_ability\n"
570 " Check whether unlocking is allowed (1) or not(0).\n"
571 "\n"
572 "advanced:\n"
573 " erase PARTITION Erase a flash partition.\n"
574 " format[:FS_TYPE[:SIZE]] PARTITION\n"
575 " Format a flash partition.\n"
576 " set_active SLOT Set the active slot.\n"
577 " oem [COMMAND...] Execute OEM-specific command.\n"
David Anderson1d504e32019-01-15 14:38:20 -0800578 " gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
David Anderson7c84b9f2019-06-27 22:15:29 -0700579 " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
580 " contain an empty set of default dynamic partitions.\n"
Luca Stefani173667b2021-04-12 19:16:43 +0200581 " create-logical-partition NAME SIZE\n"
582 " Create a logical partition with the given name and\n"
583 " size, in the super partition.\n"
584 " delete-logical-partition NAME\n"
585 " Delete a logical partition with the given name.\n"
586 " resize-logical-partition NAME SIZE\n"
587 " Change the size of the named logical partition.\n"
David Andersonab8f4662019-10-21 16:45:59 -0700588 " snapshot-update cancel On devices that support snapshot-based updates, cancel\n"
589 " an in-progress update. This may make the device\n"
590 " unbootable until it is reflashed.\n"
David Anderson220ddb12019-10-31 18:02:41 -0700591 " snapshot-update merge On devices that support snapshot-based updates, finish\n"
592 " an in-progress update if it is in the \"merging\"\n"
593 " phase.\n"
Pierre-Clément Tosi96941a02021-06-14 12:16:06 +0000594 " fetch PARTITION OUT_FILE Fetch a partition image from the device."
Elliott Hughesb76188f2018-04-03 13:30:18 -0700595 "\n"
596 "boot image:\n"
597 " boot KERNEL [RAMDISK [SECOND]]\n"
598 " Download and boot kernel from RAM.\n"
599 " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
600 " Create boot image and flash it.\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800601 " --dtb DTB Specify path to DTB for boot image header version 2.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700602 " --cmdline CMDLINE Override kernel command line.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700603 " --base ADDRESS Set kernel base address (default: 0x10000000).\n"
604 " --kernel-offset Set kernel offset (default: 0x00008000).\n"
605 " --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
606 " --tags-offset Set tags offset (default: 0x00000100).\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800607 " --dtb-offset Set dtb offset (default: 0x01100000).\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700608 " --page-size BYTES Set flash page size (default: 2048).\n"
609 " --header-version VERSION Set boot image header version.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700610 " --os-version MAJOR[.MINOR[.PATCH]]\n"
611 " Set boot image OS version (default: 0.0.0).\n"
612 " --os-patch-level YYYY-MM-DD\n"
613 " Set boot image OS security patch level.\n"
614 // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
Elliott Hughesb76188f2018-04-03 13:30:18 -0700615 "\n"
Elliott Hughes2e9b7792018-04-04 13:36:44 -0700616 // TODO: what device(s) used this? is there any documentation?
Elliott Hughesb76188f2018-04-03 13:30:18 -0700617 //" continue Continue with autoboot.\n"
618 //"\n"
619 "Android Things:\n"
620 " stage IN_FILE Sends given file to stage for the next command.\n"
621 " 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 -0800622 "\n"
623 "options:\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700624 " -w Wipe userdata.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700625 " -s SERIAL Specify a USB device.\n"
626 " -s tcp|udp:HOST[:PORT] Specify a network device.\n"
Elliott Hughes542370d2018-04-19 19:49:44 -0700627 " -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
David Anderson89569642018-11-16 15:53:35 -0800628 " --force Force a flash operation that may be unsafe.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700629 " --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
630 " non-current slot (default: current active slot).\n"
631 " --set-active[=SLOT] Sets the active slot before rebooting.\n"
632 " --skip-secondary Don't flash secondary slots in flashall/update.\n"
633 " --skip-reboot Don't reboot device after flashing.\n"
634 " --disable-verity Sets disable-verity when flashing vbmeta.\n"
635 " --disable-verification Sets disable-verification when flashing vbmeta.\n"
Jaegeuk Kim638d05e2020-11-09 08:54:13 -0800636 " --fs-options=OPTION[,OPTION]\n"
637 " Enable filesystem features. OPTION supports casefold, projid, compress\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700638 // TODO: remove --unbuffered?
639 " --unbuffered Don't buffer input or output.\n"
640 " --verbose, -v Verbose output.\n"
641 " --version Display version.\n"
642 " --help, -h Show this message.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800643 );
Yifan Hongbcd27702021-02-16 19:37:32 -0800644 // clang-format on
Elliott Hughesd6365a72017-05-08 18:04:49 -0700645 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646}
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000647
Tom Cherrydfd85df2018-09-20 14:45:05 -0700648static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
649 const std::string& second_stage) {
650 std::vector<char> kernel_data;
651 if (!ReadFileToVector(kernel, &kernel_data)) {
652 die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
653 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800654
Elliott Hughesfc797672015-04-07 20:12:50 -0700655 // Is this actually a boot image?
Steve Muckle15303f22020-03-18 14:55:06 -0700656 if (kernel_data.size() < sizeof(boot_img_hdr_v3)) {
Elliott Hughesaaa3b6b2018-01-18 16:08:24 -0800657 die("cannot load '%s': too short", kernel.c_str());
658 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700659 if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
Elliott Hughes577e8b42018-04-05 16:12:47 -0700660 if (!g_cmdline.empty()) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800661 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
Elliott Hughes577e8b42018-04-05 16:12:47 -0700662 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800663
Elliott Hughes4089d342017-10-27 14:21:12 -0700664 if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800665
Tom Cherrydfd85df2018-09-20 14:45:05 -0700666 return kernel_data;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800667 }
668
Tom Cherrydfd85df2018-09-20 14:45:05 -0700669 std::vector<char> ramdisk_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700670 if (!ramdisk.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700671 if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
672 die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
673 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800674 }
675
Tom Cherrydfd85df2018-09-20 14:45:05 -0700676 std::vector<char> second_stage_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700677 if (!second_stage.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700678 if (!ReadFileToVector(second_stage, &second_stage_data)) {
679 die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
680 }
Jeremy Compostellaa42adff2014-07-17 17:17:54 +0200681 }
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800682
683 std::vector<char> dtb_data;
684 if (!g_dtb_path.empty()) {
Steve Muckle15303f22020-03-18 14:55:06 -0700685 if (g_boot_img_hdr.header_version != 2) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000686 die("Argument dtb not supported for boot image header version %d\n",
687 g_boot_img_hdr.header_version);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800688 }
689 if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
690 die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
691 }
692 }
693
Daniel Zheng65452d02022-11-30 02:25:31 +0000694 fprintf(stderr, "creating boot image...\n");
Elliott Hughesd6365a72017-05-08 18:04:49 -0700695
Tom Cherrydfd85df2018-09-20 14:45:05 -0700696 std::vector<char> out;
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800697 mkbootimg(kernel_data, ramdisk_data, second_stage_data, dtb_data, g_base_addr, g_boot_img_hdr,
698 &out);
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800699
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800700 if (!g_cmdline.empty()) {
701 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(out.data()), g_cmdline);
702 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700703 fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700704 return out;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800705}
706
Tom Cherrydfd85df2018-09-20 14:45:05 -0700707static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
708 std::vector<char>* out) {
Elliott Hughesb4074142020-09-15 14:26:17 -0700709 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700710 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700711 fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
712 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800713 }
714
Elliott Hughesb4074142020-09-15 14:26:17 -0700715 if (zip_entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000716 die("entry '%s' is too large: %" PRIu64, entry_name.c_str(), zip_entry.uncompressed_length);
Elliott Hughesb4074142020-09-15 14:26:17 -0700717 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700718 out->resize(zip_entry.uncompressed_length);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719
Tom Cherrydfd85df2018-09-20 14:45:05 -0700720 fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
721 out->size() / 1024 / 1024);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722
Daniel Zheng65452d02022-11-30 02:25:31 +0000723 int error =
724 ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()), out->size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700725 if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000726
Tom Cherrydfd85df2018-09-20 14:45:05 -0700727 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728}
729
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700730#if defined(_WIN32)
731
732// TODO: move this to somewhere it can be shared.
733
734#include <windows.h>
735
736// Windows' tmpfile(3) requires administrator rights because
737// it creates temporary files in the root directory.
738static FILE* win32_tmpfile() {
739 char temp_path[PATH_MAX];
740 DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
741 if (nchars == 0 || nchars >= sizeof(temp_path)) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700742 die("GetTempPath failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700743 }
744
745 char filename[PATH_MAX];
746 if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700747 die("GetTempFileName failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700748 }
749
750 return fopen(filename, "w+bTD");
751}
752
753#define tmpfile win32_tmpfile
754
Elliott Hughes855cdf82018-04-02 14:24:03 -0700755static int make_temporary_fd(const char* /*what*/) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700756 // TODO: reimplement to avoid leaking a FILE*.
757 return fileno(tmpfile());
758}
759
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000760#else
761
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700762static std::string make_temporary_template() {
763 const char* tmpdir = getenv("TMPDIR");
764 if (tmpdir == nullptr) tmpdir = P_tmpdir;
765 return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
766}
767
Elliott Hughes855cdf82018-04-02 14:24:03 -0700768static int make_temporary_fd(const char* what) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700769 std::string path_template(make_temporary_template());
770 int fd = mkstemp(&path_template[0]);
771 if (fd == -1) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000772 die("failed to create temporary file for %s with template %s: %s\n", path_template.c_str(),
773 what, strerror(errno));
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700774 }
775 unlink(path_template.c_str());
776 return fd;
777}
778
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700779#endif
780
Daniel Zheng30e648b2023-05-25 15:56:29 -0700781static unique_fd UnzipToFile(ZipArchiveHandle zip, const char* entry_name) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700782 unique_fd fd(make_temporary_fd(entry_name));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700783
Elliott Hughesb4074142020-09-15 14:26:17 -0700784 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700785 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700786 fprintf(stderr, "archive does not contain '%s'\n", entry_name);
David Andersoncf444f32018-08-29 14:15:49 -0700787 errno = ENOENT;
Yifan Hongb10d0672021-02-22 15:06:27 -0800788 return unique_fd();
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000789 }
790
Elliott Hughesb4074142020-09-15 14:26:17 -0700791 fprintf(stderr, "extracting %s (%" PRIu64 " MB) to disk...", entry_name,
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700792 zip_entry.uncompressed_length / 1024 / 1024);
Elliott Hughes23af1122017-11-10 08:42:17 -0800793 double start = now();
Yifan Hong58532df2021-03-22 16:39:13 -0700794 int error = ExtractEntryToFile(zip, &zip_entry, fd.get());
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700795 if (error != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800796 die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700797 }
798
Yifan Hong58532df2021-03-22 16:39:13 -0700799 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800800 die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
Elliott Hughes4089d342017-10-27 14:21:12 -0700801 }
802
Elliott Hughes23af1122017-11-10 08:42:17 -0800803 fprintf(stderr, " took %.3fs\n", now() - start);
804
Yifan Hongb10d0672021-02-22 15:06:27 -0800805 return fd;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700806}
807
Andrew Chantd64b9882021-04-06 12:48:27 -0700808static bool CheckRequirement(const std::string& cur_product, const std::string& var,
Tom Cherry4aa60b32018-09-05 15:11:44 -0700809 const std::string& product, bool invert,
810 const std::vector<std::string>& options) {
811 Status("Checking '" + var + "'");
Elliott Hughes5620d222018-03-28 08:20:00 -0700812
Tom Cherry4aa60b32018-09-05 15:11:44 -0700813 double start = now();
814
815 if (!product.empty()) {
816 if (product != cur_product) {
817 double split = now();
818 fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
819 cur_product.c_str(), product.c_str(), (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700820 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700821 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 }
Tom Cherry4aa60b32018-09-05 15:11:44 -0700823
824 std::string var_value;
Tom Cherry9027af02018-09-24 15:48:09 -0700825 if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700826 fprintf(stderr, "FAILED\n\n");
Daniel Zheng65452d02022-11-30 02:25:31 +0000827 fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(), fb->Error().c_str());
Andrew Chantd64b9882021-04-06 12:48:27 -0700828 return false;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700829 }
830
831 bool match = false;
832 for (const auto& option : options) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000833 if (option == var_value ||
834 (option.back() == '*' &&
835 !var_value.compare(0, option.length() - 1, option, 0, option.length() - 1))) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700836 match = true;
837 break;
838 }
839 }
840
841 if (invert) {
842 match = !match;
843 }
844
845 if (match) {
846 double split = now();
847 fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700848 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700849 }
850
851 fprintf(stderr, "FAILED\n\n");
852 fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
853 fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
854 for (auto it = std::next(options.begin()); it != options.end(); ++it) {
855 fprintf(stderr, " or '%s'", it->c_str());
856 }
857 fprintf(stderr, ".\n\n");
Andrew Chantd64b9882021-04-06 12:48:27 -0700858 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859}
860
Tom Cherry4aa60b32018-09-05 15:11:44 -0700861bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
862 bool* invert, std::vector<std::string>* options) {
Elliott Hughes5620d222018-03-28 08:20:00 -0700863 // "require product=alpha|beta|gamma"
864 // "require version-bootloader=1234"
865 // "require-for-product:gamma version-bootloader=istanbul|constantinople"
866 // "require partition-exists=vendor"
Tom Cherry4aa60b32018-09-05 15:11:44 -0700867 *product = "";
868 *invert = false;
Elliott Hughes5620d222018-03-28 08:20:00 -0700869
Tom Cherry4aa60b32018-09-05 15:11:44 -0700870 auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
871 auto require_product_regex =
872 std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
873 std::smatch match_results;
874
875 if (std::regex_match(line, match_results, require_reject_regex)) {
876 *invert = Trim(match_results[1]) == "reject";
877 } else if (std::regex_match(line, match_results, require_product_regex)) {
878 *product = match_results[1];
879 } else {
880 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800881 }
882
Tom Cherry4aa60b32018-09-05 15:11:44 -0700883 *name = match_results[2];
Elliott Hughes253c18d2015-03-18 22:47:09 -0700884 // Work around an unfortunate name mismatch.
Tom Cherry4aa60b32018-09-05 15:11:44 -0700885 if (*name == "board") {
886 *name = "product";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800887 }
888
Tom Cherry4aa60b32018-09-05 15:11:44 -0700889 auto raw_options = Split(match_results[3], "|");
890 for (const auto& option : raw_options) {
891 auto trimmed_option = Trim(option);
892 options->emplace_back(trimmed_option);
893 }
894
895 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800896}
897
Tom Cherry4aa60b32018-09-05 15:11:44 -0700898// "require partition-exists=x" is a special case, added because of the trouble we had when
899// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
900// missing out new partitions. A device with new partitions can use "partition-exists" to
901// override the fields `optional_if_no_image` in the `images` array.
902static void HandlePartitionExists(const std::vector<std::string>& options) {
903 const std::string& partition_name = options[0];
904 std::string has_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700905 if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
Tom Cherry4aa60b32018-09-05 15:11:44 -0700906 (has_slot != "yes" && has_slot != "no")) {
907 die("device doesn't have required partition %s!", partition_name.c_str());
908 }
909 bool known_partition = false;
Daniel Zheng65452d02022-11-30 02:25:31 +0000910 for (size_t i = 0; i < images.size(); ++i) {
911 if (!images[i].nickname.empty() && images[i].nickname == partition_name) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700912 images[i].optional_if_no_image = false;
913 known_partition = true;
914 }
915 }
916 if (!known_partition) {
917 die("device requires partition %s which is not known to this version of fastboot",
918 partition_name.c_str());
919 }
920}
921
Andrew Chantd64b9882021-04-06 12:48:27 -0700922static void CheckRequirements(const std::string& data, bool force_flash) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700923 std::string cur_product;
Tom Cherry9027af02018-09-24 15:48:09 -0700924 if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
925 fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700926 }
927
928 auto lines = Split(data, "\n");
929 for (const auto& line : lines) {
930 if (line.empty()) {
931 continue;
932 }
933
934 std::string name;
935 std::string product;
936 bool invert;
937 std::vector<std::string> options;
938
939 if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
940 fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
941 continue;
942 }
943 if (name == "partition-exists") {
944 HandlePartitionExists(options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800945 } else {
Andrew Chantd64b9882021-04-06 12:48:27 -0700946 bool met = CheckRequirement(cur_product, name, product, invert, options);
947 if (!met) {
948 if (!force_flash) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000949 die("requirements not met!");
Andrew Chantd64b9882021-04-06 12:48:27 -0700950 } else {
Daniel Zheng65452d02022-11-30 02:25:31 +0000951 fprintf(stderr, "requirements not met! but proceeding due to --force\n");
Andrew Chantd64b9882021-04-06 12:48:27 -0700952 }
953 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954 }
955 }
956}
957
Tom Cherry9027af02018-09-24 15:48:09 -0700958static void DisplayVarOrError(const std::string& label, const std::string& var) {
959 std::string value;
960
961 if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
962 Status("getvar:" + var);
963 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
964 return;
965 }
966 fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
967}
968
969static void DumpInfo() {
970 fprintf(stderr, "--------------------------------------------\n");
971 DisplayVarOrError("Bootloader Version...", "version-bootloader");
972 DisplayVarOrError("Baseband Version.....", "version-baseband");
973 DisplayVarOrError("Serial Number........", "serialno");
974 fprintf(stderr, "--------------------------------------------\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800975}
976
Daniel Zheng47d70a52023-02-14 17:44:40 +0000977std::vector<SparsePtr> resparse_file(sparse_file* s, int64_t max_size) {
Tao Bao41cf35f2018-04-24 10:54:21 -0700978 if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000979 die("invalid max size %" PRId64, max_size);
Tao Bao41cf35f2018-04-24 10:54:21 -0700980 }
981
David Andersonaa87dc52023-01-27 20:39:06 -0800982 const int files = sparse_file_resparse(s, max_size, nullptr, 0);
David Anderson74c78072023-03-16 21:21:28 -0700983 if (files < 0) die("Failed to compute resparse boundaries");
Colin Crossf8387882012-05-24 17:18:41 -0700984
David Andersona1c983e2023-01-27 11:57:27 -0800985 auto temp = std::make_unique<sparse_file*[]>(files);
David Andersonaa87dc52023-01-27 20:39:06 -0800986 const int rv = sparse_file_resparse(s, max_size, temp.get(), files);
David Andersona1c983e2023-01-27 11:57:27 -0800987 if (rv < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700988
David Andersona1c983e2023-01-27 11:57:27 -0800989 std::vector<SparsePtr> out_s;
990 for (int i = 0; i < files; i++) {
991 out_s.emplace_back(temp[i], sparse_file_destroy);
992 }
Colin Crossf8387882012-05-24 17:18:41 -0700993 return out_s;
994}
995
David Andersonaa87dc52023-01-27 20:39:06 -0800996static std::vector<SparsePtr> load_sparse_files(int fd, int64_t max_size) {
997 SparsePtr s(sparse_file_import_auto(fd, false, true), sparse_file_destroy);
998 if (!s) die("cannot sparse read file");
999
1000 return resparse_file(s.get(), max_size);
1001}
1002
Yifan Hongbcd27702021-02-16 19:37:32 -08001003static uint64_t get_uint_var(const char* var_name) {
1004 std::string value_str;
1005 if (fb->GetVar(var_name, &value_str) != fastboot::SUCCESS || value_str.empty()) {
1006 verbose("target didn't report %s", var_name);
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001007 return 0;
Colin Crossf8387882012-05-24 17:18:41 -07001008 }
1009
Elliott Hughes77c0e662015-11-02 15:51:12 -08001010 // Some bootloaders (angler, for example) send spurious whitespace too.
Yifan Hongbcd27702021-02-16 19:37:32 -08001011 value_str = android::base::Trim(value_str);
Elliott Hughes77c0e662015-11-02 15:51:12 -08001012
Yifan Hongbcd27702021-02-16 19:37:32 -08001013 uint64_t value;
1014 if (!android::base::ParseUint(value_str, &value)) {
1015 fprintf(stderr, "couldn't parse %s '%s'\n", var_name, value_str.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001016 return 0;
1017 }
Yifan Hongbcd27702021-02-16 19:37:32 -08001018 if (value > 0) verbose("target reported %s of %" PRId64 " bytes", var_name, value);
1019 return value;
Colin Crossf8387882012-05-24 17:18:41 -07001020}
1021
Daniel Zheng5769b262023-06-21 14:41:11 -07001022int64_t get_sparse_limit(int64_t size, const FlashingPlan* fp) {
1023 int64_t limit = int64_t(fp->sparse_limit);
Elliott Hughes542370d2018-04-19 19:49:44 -07001024 if (limit == 0) {
1025 // Unlimited, so see what the target device's limit is.
1026 // TODO: shouldn't we apply this limit even if you've used -S?
Colin Crossf8387882012-05-24 17:18:41 -07001027 if (target_sparse_limit == -1) {
Yifan Hongbcd27702021-02-16 19:37:32 -08001028 target_sparse_limit = static_cast<int64_t>(get_uint_var("max-download-size"));
Colin Crossf8387882012-05-24 17:18:41 -07001029 }
1030 if (target_sparse_limit > 0) {
1031 limit = target_sparse_limit;
1032 } else {
Colin Cross0bbfb392012-07-24 18:05:21 -07001033 return 0;
Colin Crossf8387882012-05-24 17:18:41 -07001034 }
1035 }
1036
1037 if (size > limit) {
Chris Fries6a999712017-04-04 09:52:47 -05001038 return std::min(limit, RESPARSE_LIMIT);
Colin Crossf8387882012-05-24 17:18:41 -07001039 }
1040
1041 return 0;
1042}
1043
Daniel Zheng5769b262023-06-21 14:41:11 -07001044static bool load_buf_fd(unique_fd fd, struct fastboot_buffer* buf, const FlashingPlan* fp) {
Elliott Hughesfc797672015-04-07 20:12:50 -07001045 int64_t sz = get_file_size(fd);
1046 if (sz == -1) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001047 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -07001048 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001049
Yifan Hong58532df2021-03-22 16:39:13 -07001050 if (sparse_file* s = sparse_file_import(fd.get(), false, false)) {
David Anderson32e376f2018-08-16 13:43:11 -07001051 buf->image_size = sparse_file_len(s, false, false);
David Anderson74c78072023-03-16 21:21:28 -07001052 if (buf->image_size < 0) {
1053 LOG(ERROR) << "Could not compute length of sparse file";
1054 return false;
1055 }
David Anderson32e376f2018-08-16 13:43:11 -07001056 sparse_file_destroy(s);
1057 } else {
1058 buf->image_size = sz;
1059 }
1060
Yifan Hong58532df2021-03-22 16:39:13 -07001061 lseek(fd.get(), 0, SEEK_SET);
Daniel Zheng5769b262023-06-21 14:41:11 -07001062 int64_t limit = get_sparse_limit(sz, fp);
Yifan Honge9f067b2021-03-22 16:55:39 -07001063 buf->fd = std::move(fd);
Colin Crossf8387882012-05-24 17:18:41 -07001064 if (limit) {
David Andersona1c983e2023-01-27 11:57:27 -08001065 buf->files = load_sparse_files(buf->fd.get(), limit);
1066 if (buf->files.empty()) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001067 return false;
Colin Crossf8387882012-05-24 17:18:41 -07001068 }
Rom Lemarchand622810c2013-06-28 09:54:59 -07001069 buf->type = FB_BUFFER_SPARSE;
Colin Crossf8387882012-05-24 17:18:41 -07001070 } else {
Chris Fries0ea946c2017-04-12 10:25:57 -05001071 buf->type = FB_BUFFER_FD;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +00001072 buf->sz = sz;
Colin Crossf8387882012-05-24 17:18:41 -07001073 }
Rom Lemarchand622810c2013-06-28 09:54:59 -07001074
Elliott Hughes53ec4952016-05-11 12:39:27 -07001075 return true;
Rom Lemarchand622810c2013-06-28 09:54:59 -07001076}
1077
Daniel Zheng5769b262023-06-21 14:41:11 -07001078static bool load_buf(const char* fname, struct fastboot_buffer* buf, const FlashingPlan* fp) {
Chris Fries0ea946c2017-04-12 10:25:57 -05001079 unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
1080
Elliott Hughes53ec4952016-05-11 12:39:27 -07001081 if (fd == -1) {
Daniel Zheng59c22c32023-06-21 14:30:46 -07001082 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -07001083 }
Chris Fries0ea946c2017-04-12 10:25:57 -05001084
1085 struct stat s;
Yifan Hong58532df2021-03-22 16:39:13 -07001086 if (fstat(fd.get(), &s)) {
Chris Fries0ea946c2017-04-12 10:25:57 -05001087 return false;
1088 }
1089 if (!S_ISREG(s.st_mode)) {
1090 errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
1091 return false;
1092 }
1093
Daniel Zheng5769b262023-06-21 14:41:11 -07001094 return load_buf_fd(std::move(fd), buf, fp);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001095}
1096
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001097static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf, bool vbmeta_in_boot) {
David Zeuthenb6ea4352017-08-07 14:29:26 -04001098 // Buffer needs to be at least the size of the VBMeta struct which
1099 // is 256 bytes.
1100 if (buf->sz < 256) {
1101 return;
1102 }
1103
David Zeuthenb6ea4352017-08-07 14:29:26 -04001104 std::string data;
1105 if (!android::base::ReadFdToString(buf->fd, &data)) {
1106 die("Failed reading from vbmeta");
1107 }
1108
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001109 uint64_t vbmeta_offset = 0;
1110 if (vbmeta_in_boot) {
1111 // Tries to locate top-level vbmeta from boot.img footer.
1112 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
1113 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
Bowgo Tsai671249a2021-08-10 16:32:37 +08001114 die("Failed to find AVB_FOOTER at offset: %" PRId64 ", is BOARD_AVB_ENABLE true?",
1115 footer_offset);
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001116 }
1117 const AvbFooter* footer = reinterpret_cast<const AvbFooter*>(data.c_str() + footer_offset);
1118 vbmeta_offset = be64toh(footer->vbmeta_offset);
1119 }
1120 // Ensures there is AVB_MAGIC at vbmeta_offset.
1121 if (0 != data.compare(vbmeta_offset, AVB_MAGIC_LEN, AVB_MAGIC)) {
1122 die("Failed to find AVB_MAGIC at offset: %" PRId64, vbmeta_offset);
1123 }
1124
1125 fprintf(stderr, "Rewriting vbmeta struct at offset: %" PRId64 "\n", vbmeta_offset);
1126
David Zeuthenb6ea4352017-08-07 14:29:26 -04001127 // There's a 32-bit big endian |flags| field at offset 120 where
1128 // bit 0 corresponds to disable-verity and bit 1 corresponds to
1129 // disable-verification.
1130 //
1131 // See external/avb/libavb/avb_vbmeta_image.h for the layout of
1132 // the VBMeta struct.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001133 uint64_t flags_offset = 123 + vbmeta_offset;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001134 if (g_disable_verity) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001135 data[flags_offset] |= 0x01;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001136 }
1137 if (g_disable_verification) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001138 data[flags_offset] |= 0x02;
David Zeuthenb6ea4352017-08-07 14:29:26 -04001139 }
1140
Yifan Hongb10d0672021-02-22 15:06:27 -08001141 unique_fd fd(make_temporary_fd("vbmeta rewriting"));
David Zeuthenb6ea4352017-08-07 14:29:26 -04001142 if (!android::base::WriteStringToFd(data, fd)) {
1143 die("Failed writing to modified vbmeta");
1144 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001145 buf->fd = std::move(fd);
Yifan Hong58532df2021-03-22 16:39:13 -07001146 lseek(buf->fd.get(), 0, SEEK_SET);
David Zeuthenb6ea4352017-08-07 14:29:26 -04001147}
1148
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001149static bool has_vbmeta_partition() {
1150 std::string partition_type;
1151 return fb->GetVar("partition-type:vbmeta", &partition_type) == fastboot::SUCCESS ||
1152 fb->GetVar("partition-type:vbmeta_a", &partition_type) == fastboot::SUCCESS ||
1153 fb->GetVar("partition-type:vbmeta_b", &partition_type) == fastboot::SUCCESS;
1154}
1155
Daniel Zheng403657d2023-03-10 07:37:25 +00001156static bool is_vbmeta_partition(const std::string& partition) {
1157 return android::base::EndsWith(partition, "vbmeta") ||
1158 android::base::EndsWith(partition, "vbmeta_a") ||
1159 android::base::EndsWith(partition, "vbmeta_b");
1160}
1161
David Andersonaa87dc52023-01-27 20:39:06 -08001162// Note: this only works in userspace fastboot. In the bootloader, use
1163// should_flash_in_userspace().
Daniel Zheng47d70a52023-02-14 17:44:40 +00001164bool is_logical(const std::string& partition) {
Michael Bestasa495be72020-11-06 17:58:28 +02001165 std::string value;
1166 return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1167}
1168
Yifan Hongbcd27702021-02-16 19:37:32 -08001169static uint64_t get_partition_size(const std::string& partition) {
Steve Muckle3af575b2020-06-18 17:02:15 -07001170 std::string partition_size_str;
1171 if (fb->GetVar("partition-size:" + partition, &partition_size_str) != fastboot::SUCCESS) {
Michael Bestasa495be72020-11-06 17:58:28 +02001172 if (!is_logical(partition)) {
1173 return 0;
1174 }
Yifan Hong60de9692021-02-17 13:51:54 -08001175 die("cannot get partition size for %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001176 }
1177
1178 partition_size_str = fb_fix_numeric_var(partition_size_str);
Yifan Hongbcd27702021-02-16 19:37:32 -08001179 uint64_t partition_size;
1180 if (!android::base::ParseUint(partition_size_str, &partition_size)) {
Michael Bestasa495be72020-11-06 17:58:28 +02001181 if (!is_logical(partition)) {
1182 return 0;
1183 }
Steve Muckle3af575b2020-06-18 17:02:15 -07001184 die("Couldn't parse partition size '%s'.", partition_size_str.c_str());
1185 }
Yifan Hongbcd27702021-02-16 19:37:32 -08001186 return partition_size;
1187}
1188
Devin Moorecb5098f2022-01-07 16:33:46 +00001189static void copy_avb_footer(const std::string& partition, struct fastboot_buffer* buf) {
Daniel Zhenge33e8a82023-03-29 04:20:48 +00001190 if (buf->sz < AVB_FOOTER_SIZE || is_logical(partition) ||
1191 should_flash_in_userspace(partition)) {
Yifan Hongbcd27702021-02-16 19:37:32 -08001192 return;
1193 }
Bowgo Tsai671249a2021-08-10 16:32:37 +08001194 // If overflows and negative, it should be < buf->sz.
1195 int64_t partition_size = static_cast<int64_t>(get_partition_size(partition));
1196
1197 if (partition_size == buf->sz) {
1198 return;
1199 }
1200 // Some device bootloaders might not implement `fastboot getvar partition-size:boot[_a|_b]`.
1201 // In this case, partition_size will be zero.
1202 if (partition_size < buf->sz) {
1203 fprintf(stderr,
Devin Moorecb5098f2022-01-07 16:33:46 +00001204 "Warning: skip copying %s image avb footer"
1205 " (%s partition size: %" PRId64 ", %s image size: %" PRId64 ").\n",
1206 partition.c_str(), partition.c_str(), partition_size, partition.c_str(), buf->sz);
Bowgo Tsai671249a2021-08-10 16:32:37 +08001207 return;
1208 }
1209
1210 // IMPORTANT: after the following read, we need to reset buf->fd before return (if not die).
1211 // Because buf->fd will still be used afterwards.
Steve Muckle3af575b2020-06-18 17:02:15 -07001212 std::string data;
1213 if (!android::base::ReadFdToString(buf->fd, &data)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001214 die("Failed reading from %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001215 }
1216
1217 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
1218 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
Bowgo Tsai671249a2021-08-10 16:32:37 +08001219 lseek(buf->fd.get(), 0, SEEK_SET); // IMPORTANT: resets buf->fd before return.
Steve Muckle3af575b2020-06-18 17:02:15 -07001220 return;
1221 }
1222
Devin Moorecb5098f2022-01-07 16:33:46 +00001223 const std::string tmp_fd_template = partition + " rewriting";
1224 unique_fd fd(make_temporary_fd(tmp_fd_template.c_str()));
Steve Muckle3af575b2020-06-18 17:02:15 -07001225 if (!android::base::WriteStringToFd(data, fd)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001226 die("Failed writing to modified %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001227 }
Yifan Hong58532df2021-03-22 16:39:13 -07001228 lseek(fd.get(), partition_size - AVB_FOOTER_SIZE, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001229 if (!android::base::WriteStringToFd(data.substr(footer_offset), fd)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001230 die("Failed copying AVB footer in %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001231 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001232 buf->fd = std::move(fd);
Steve Muckle3af575b2020-06-18 17:02:15 -07001233 buf->sz = partition_size;
Yifan Hong58532df2021-03-22 16:39:13 -07001234 lseek(buf->fd.get(), 0, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001235}
1236
Daniel Zheng47d70a52023-02-14 17:44:40 +00001237void flash_partition_files(const std::string& partition, const std::vector<SparsePtr>& files) {
David Andersonaa87dc52023-01-27 20:39:06 -08001238 for (size_t i = 0; i < files.size(); i++) {
1239 sparse_file* s = files[i].get();
1240 int64_t sz = sparse_file_len(s, true, false);
David Anderson74c78072023-03-16 21:21:28 -07001241 if (sz < 0) {
1242 LOG(FATAL) << "Could not compute length of sparse image for " << partition;
1243 }
David Andersonaa87dc52023-01-27 20:39:06 -08001244 fb->FlashPartition(partition, s, sz, i + 1, files.size());
1245 }
1246}
1247
Daniel Zheng403657d2023-03-10 07:37:25 +00001248static void flash_buf(const std::string& partition, struct fastboot_buffer* buf,
1249 const bool apply_vbmeta) {
Daniel Zheng980985a2023-03-14 17:20:08 +00001250 copy_avb_footer(partition, buf);
Steve Muckle3af575b2020-06-18 17:02:15 -07001251
David Zeuthenb6ea4352017-08-07 14:29:26 -04001252 // Rewrite vbmeta if that's what we're flashing and modification has been requested.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001253 if (g_disable_verity || g_disable_verification) {
Paweł Grabasff9cfac2021-03-04 13:11:25 +01001254 // The vbmeta partition might have additional prefix if running in virtual machine
1255 // e.g., guest_vbmeta_a.
Daniel Zheng403657d2023-03-10 07:37:25 +00001256 if (apply_vbmeta) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001257 rewrite_vbmeta_buffer(buf, false /* vbmeta_in_boot */);
1258 } else if (!has_vbmeta_partition() &&
1259 (partition == "boot" || partition == "boot_a" || partition == "boot_b")) {
Daniel Zheng65452d02022-11-30 02:25:31 +00001260 rewrite_vbmeta_buffer(buf, true /* vbmeta_in_boot */);
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001261 }
David Zeuthenb6ea4352017-08-07 14:29:26 -04001262 }
1263
Rom Lemarchand622810c2013-06-28 09:54:59 -07001264 switch (buf->type) {
Josh Gao9da9ac52016-01-19 14:50:18 -08001265 case FB_BUFFER_SPARSE: {
David Andersonaa87dc52023-01-27 20:39:06 -08001266 flash_partition_files(partition, buf->files);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001267 break;
Josh Gao9da9ac52016-01-19 14:50:18 -08001268 }
Chris Fries0ea946c2017-04-12 10:25:57 -05001269 case FB_BUFFER_FD:
Tom Cherry9027af02018-09-24 15:48:09 -07001270 fb->FlashPartition(partition, buf->fd, buf->sz);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001271 break;
1272 default:
1273 die("unknown buffer type: %d", buf->type);
1274 }
1275}
1276
Daniel Zheng29a211c2023-03-10 07:23:49 +00001277std::string get_current_slot() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001278 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07001279 if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
LuK1337dae48ef2020-04-06 14:38:58 +02001280 if (current_slot[0] == '_') current_slot.erase(0, 1);
Elliott Hughes42b18a52018-04-10 15:32:21 -07001281 return current_slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001282}
1283
Aaron Wisnerdb511202018-06-26 15:38:35 -05001284static int get_slot_count() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001285 std::string var;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001286 int count = 0;
Tom Cherry9027af02018-09-24 15:48:09 -07001287 if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
1288 !android::base::ParseInt(var, &count)) {
Elliott Hughes42b18a52018-04-10 15:32:21 -07001289 return 0;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001290 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001291 return count;
1292}
1293
Daniel Zheng47d70a52023-02-14 17:44:40 +00001294bool supports_AB() {
Daniel Zheng65452d02022-11-30 02:25:31 +00001295 return get_slot_count() >= 2;
Alex Lightbb9b8a52016-06-29 09:26:44 -07001296}
1297
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001298// Given a current slot, this returns what the 'other' slot is.
Daniel Rosenberg80919472016-06-30 19:25:31 -07001299static std::string get_other_slot(const std::string& current_slot, int count) {
1300 if (count == 0) return "";
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001301
Daniel Zheng65452d02022-11-30 02:25:31 +00001302 char next = (current_slot[0] - 'a' + 1) % count + 'a';
Daniel Rosenberg80919472016-06-30 19:25:31 -07001303 return std::string(1, next);
1304}
1305
Aaron Wisnerdb511202018-06-26 15:38:35 -05001306static std::string get_other_slot(const std::string& current_slot) {
1307 return get_other_slot(current_slot, get_slot_count());
Daniel Rosenberg80919472016-06-30 19:25:31 -07001308}
1309
Aaron Wisnerdb511202018-06-26 15:38:35 -05001310static std::string get_other_slot(int count) {
1311 return get_other_slot(get_current_slot(), count);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001312}
1313
Aaron Wisnerdb511202018-06-26 15:38:35 -05001314static std::string get_other_slot() {
1315 return get_other_slot(get_current_slot(), get_slot_count());
Alex Lightbb9b8a52016-06-29 09:26:44 -07001316}
1317
Aaron Wisnerdb511202018-06-26 15:38:35 -05001318static std::string verify_slot(const std::string& slot_name, bool allow_all) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001319 std::string slot = slot_name;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001320 if (slot == "all") {
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001321 if (allow_all) {
1322 return "all";
1323 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001324 int count = get_slot_count();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001325 if (count > 0) {
1326 return "a";
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001327 } else {
Elliott Hughes4089d342017-10-27 14:21:12 -07001328 die("No known slots");
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001329 }
1330 }
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001331 }
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001332
Aaron Wisnerdb511202018-06-26 15:38:35 -05001333 int count = get_slot_count();
Elliott Hughes4089d342017-10-27 14:21:12 -07001334 if (count == 0) die("Device does not support slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001335
Daniel Rosenberg80919472016-06-30 19:25:31 -07001336 if (slot == "other") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001337 std::string other = get_other_slot(count);
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001338 if (other == "") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001339 die("No known slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001340 }
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001341 return other;
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001342 }
1343
Daniel Zheng65452d02022-11-30 02:25:31 +00001344 if (slot.size() == 1 && (slot[0] - 'a' >= 0 && slot[0] - 'a' < count)) return slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001345
1346 fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
Daniel Zheng65452d02022-11-30 02:25:31 +00001347 for (int i = 0; i < count; i++) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001348 fprintf(stderr, "%c\n", (char)(i + 'a'));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001349 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001350
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001351 exit(1);
1352}
1353
Aaron Wisnerdb511202018-06-26 15:38:35 -05001354static std::string verify_slot(const std::string& slot) {
Daniel Zheng65452d02022-11-30 02:25:31 +00001355 return verify_slot(slot, true);
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001356}
1357
Aaron Wisnerdb511202018-06-26 15:38:35 -05001358static void do_for_partition(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001359 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001360 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001361 std::string current_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001362 // |part| can be vendor_boot:default. Append slot to the first token.
1363 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001364
Yifan Hong6d7da632021-02-23 12:15:51 -08001365 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001366 /* If has-slot is not supported, the answer is no. */
1367 has_slot = "no";
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001368 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001369 if (has_slot == "yes") {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001370 if (slot == "") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001371 current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001372 if (current_slot == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001373 die("Failed to identify current slot");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001374 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001375 part_tokens[0] += "_" + current_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001376 } else {
Yifan Hong6d7da632021-02-23 12:15:51 -08001377 part_tokens[0] += "_" + slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001378 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001379 func(android::base::Join(part_tokens, ":"));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001380 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001381 if (force_slot && slot != "") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001382 fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
1383 part_tokens[0].c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001384 }
1385 func(part);
1386 }
1387}
1388
David Pursell0b156632015-10-30 11:22:01 -07001389/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1390 * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1391 * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1392 * partition does not support slots.
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001393 */
Daniel Zheng0d307182023-01-31 21:07:53 +00001394void do_for_partitions(const std::string& part, const std::string& slot,
1395 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001396 std::string has_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001397 // |part| can be vendor_boot:default. Query has-slot on the first token only.
1398 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001399
Daniel Rosenberg80919472016-06-30 19:25:31 -07001400 if (slot == "all") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001401 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
1402 die("Could not check if partition %s has slot %s", part_tokens[0].c_str(),
1403 slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001404 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001405 if (has_slot == "yes") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001406 for (int i = 0; i < get_slot_count(); i++) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001407 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001408 }
1409 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001410 do_for_partition(part, "", func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001411 }
1412 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001413 do_for_partition(part, slot, func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001414 }
1415}
1416
Daniel Zheng47d70a52023-02-14 17:44:40 +00001417bool is_retrofit_device() {
David Anderson0c732342018-11-28 17:10:42 -08001418 std::string value;
1419 if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1420 return false;
1421 }
1422 return android::base::StartsWith(value, "system_");
1423}
1424
Yifan Hongbcd27702021-02-16 19:37:32 -08001425// Fetch a partition from the device to a given fd. This is a wrapper over FetchToFd to fetch
1426// the full image.
1427static uint64_t fetch_partition(const std::string& partition, borrowed_fd fd) {
1428 uint64_t fetch_size = get_uint_var(FB_VAR_MAX_FETCH_SIZE);
1429 if (fetch_size == 0) {
1430 die("Unable to get %s. Device does not support fetch command.", FB_VAR_MAX_FETCH_SIZE);
1431 }
1432 uint64_t partition_size = get_partition_size(partition);
1433 if (partition_size <= 0) {
1434 die("Invalid partition size for partition %s: %" PRId64, partition.c_str(), partition_size);
1435 }
1436
1437 uint64_t offset = 0;
1438 while (offset < partition_size) {
1439 uint64_t chunk_size = std::min(fetch_size, partition_size - offset);
1440 if (fb->FetchToFd(partition, fd, offset, chunk_size) != fastboot::RetCode::SUCCESS) {
1441 die("Unable to fetch %s (offset=%" PRIx64 ", size=%" PRIx64 ")", partition.c_str(),
1442 offset, chunk_size);
1443 }
1444 offset += chunk_size;
1445 }
1446 return partition_size;
1447}
1448
1449static void do_fetch(const std::string& partition, const std::string& slot_override,
1450 const std::string& outfile) {
1451 unique_fd fd(TEMP_FAILURE_RETRY(
1452 open(outfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0644)));
1453 auto fetch = std::bind(fetch_partition, _1, borrowed_fd(fd));
1454 do_for_partitions(partition, slot_override, fetch, false /* force slot */);
1455}
1456
Yifan Honge71fe242021-02-22 15:00:15 -08001457// Return immediately if not flashing a vendor boot image. If flashing a vendor boot image,
1458// repack vendor_boot image with an updated ramdisk. After execution, buf is set
1459// to the new image to flash, and return value is the real partition name to flash.
1460static std::string repack_ramdisk(const char* pname, struct fastboot_buffer* buf) {
1461 std::string_view pname_sv{pname};
1462
1463 if (!android::base::StartsWith(pname_sv, "vendor_boot:") &&
1464 !android::base::StartsWith(pname_sv, "vendor_boot_a:") &&
1465 !android::base::StartsWith(pname_sv, "vendor_boot_b:")) {
1466 return std::string(pname_sv);
1467 }
1468 if (buf->type != FB_BUFFER_FD) {
1469 die("Flashing sparse vendor ramdisk image is not supported.");
1470 }
1471 if (buf->sz <= 0) {
1472 die("repack_ramdisk() sees negative size: %" PRId64, buf->sz);
1473 }
1474 std::string partition(pname_sv.substr(0, pname_sv.find(':')));
1475 std::string ramdisk(pname_sv.substr(pname_sv.find(':') + 1));
1476
1477 unique_fd vendor_boot(make_temporary_fd("vendor boot repack"));
1478 uint64_t vendor_boot_size = fetch_partition(partition, vendor_boot);
1479 auto repack_res = replace_vendor_ramdisk(vendor_boot, vendor_boot_size, ramdisk, buf->fd,
1480 static_cast<uint64_t>(buf->sz));
1481 if (!repack_res.ok()) {
1482 die("%s", repack_res.error().message().c_str());
1483 }
1484
1485 buf->fd = std::move(vendor_boot);
1486 buf->sz = vendor_boot_size;
1487 buf->image_size = vendor_boot_size;
1488 return partition;
1489}
1490
Daniel Zheng791a83b2023-05-23 10:42:39 -07001491void do_flash(const char* pname, const char* fname, const bool apply_vbmeta,
1492 const FlashingPlan* fp) {
Yifan Hong6d7da632021-02-23 12:15:51 -08001493 verbose("Do flash %s %s", pname, fname);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001494 struct fastboot_buffer buf;
1495
Daniel Zheng5769b262023-06-21 14:41:11 -07001496 if (fp && fp->source) {
Daniel Zheng791a83b2023-05-23 10:42:39 -07001497 unique_fd fd = fp->source->OpenFile(fname);
Daniel Zheng5769b262023-06-21 14:41:11 -07001498 if (fd < 0 || !load_buf_fd(std::move(fd), &buf, fp)) {
Daniel Zheng791a83b2023-05-23 10:42:39 -07001499 die("could not load '%s': %s", fname, strerror(errno));
1500 }
Daniel Zhengba07ef52023-06-21 14:14:19 -07001501 std::vector<char> signature_data;
1502 std::string file_string(fname);
1503 if (fp->source->ReadFile(file_string.substr(0, file_string.find('.')) + ".sig",
1504 &signature_data)) {
1505 fb->Download("signature", signature_data);
1506 fb->RawCommand("signature", "installing signature");
1507 }
Daniel Zheng5769b262023-06-21 14:41:11 -07001508 } else if (!load_buf(fname, &buf, fp)) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001509 die("cannot load '%s': %s", fname, strerror(errno));
Rom Lemarchand622810c2013-06-28 09:54:59 -07001510 }
Daniel Zheng791a83b2023-05-23 10:42:39 -07001511
David Anderson629e51c2018-10-25 12:51:25 -07001512 if (is_logical(pname)) {
1513 fb->ResizePartition(pname, std::to_string(buf.image_size));
1514 }
Yifan Honge71fe242021-02-22 15:00:15 -08001515 std::string flash_pname = repack_ramdisk(pname, &buf);
Daniel Zheng403657d2023-03-10 07:37:25 +00001516 flash_buf(flash_pname, &buf, apply_vbmeta);
Colin Crossf8387882012-05-24 17:18:41 -07001517}
1518
Daniel Rosenberg13454092016-06-27 19:43:11 -07001519// Sets slot_override as the active slot. If slot_override is blank,
1520// set current slot as active instead. This clears slot-unbootable.
Aaron Wisnerdb511202018-06-26 15:38:35 -05001521static void set_active(const std::string& slot_override) {
1522 if (!supports_AB()) return;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001523
Daniel Rosenberg80919472016-06-30 19:25:31 -07001524 if (slot_override != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001525 fb->SetActive(slot_override);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001526 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001527 std::string current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001528 if (current_slot != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001529 fb->SetActive(current_slot);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001530 }
1531 }
1532}
1533
Daniel Zheng0d307182023-01-31 21:07:53 +00001534bool is_userspace_fastboot() {
David Anderson32e376f2018-08-16 13:43:11 -07001535 std::string value;
Tom Cherry9027af02018-09-24 15:48:09 -07001536 return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
David Anderson32e376f2018-08-16 13:43:11 -07001537}
1538
Daniel Zheng0d307182023-01-31 21:07:53 +00001539void reboot_to_userspace_fastboot() {
Tom Cherry9027af02018-09-24 15:48:09 -07001540 fb->RebootTo("fastboot");
1541
1542 auto* old_transport = fb->set_transport(nullptr);
1543 delete old_transport;
David Anderson1d887432018-08-27 16:47:32 -07001544
1545 // Give the current connection time to close.
Dmitrii Merkurev47855542023-02-28 21:02:48 +00001546 std::this_thread::sleep_for(std::chrono::seconds(1));
David Anderson1d887432018-08-27 16:47:32 -07001547
Tom Cherry9027af02018-09-24 15:48:09 -07001548 fb->set_transport(open_device());
David Anderson11d6d272018-12-07 16:39:07 -08001549
1550 if (!is_userspace_fastboot()) {
1551 die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1552 }
Hridya Valsaraju83d856e2019-05-17 14:24:19 -07001553
1554 // Reset target_sparse_limit after reboot to userspace fastboot. Max
1555 // download sizes may differ in bootloader and fastbootd.
1556 target_sparse_limit = -1;
David Anderson1d887432018-08-27 16:47:32 -07001557}
1558
David Andersonab8f4662019-10-21 16:45:59 -07001559static void CancelSnapshotIfNeeded() {
1560 std::string merge_status = "none";
1561 if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
Elliott Hughes6a7ff582020-06-05 14:06:15 -07001562 !merge_status.empty() && merge_status != "none") {
Yifan Hong712c32b2019-12-10 18:11:13 -08001563 fb->SnapshotUpdateCommand("cancel");
David Andersonab8f4662019-10-21 16:45:59 -07001564 }
1565}
1566
Daniel Zheng29a211c2023-03-10 07:23:49 +00001567std::string GetPartitionName(const ImageEntry& entry, const std::string& current_slot) {
Daniel Zheng47d70a52023-02-14 17:44:40 +00001568 auto slot = entry.second;
1569 if (slot.empty()) {
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001570 slot = current_slot;
Daniel Zheng47d70a52023-02-14 17:44:40 +00001571 }
1572 if (slot.empty()) {
1573 return entry.first->part_name;
1574 }
1575 if (slot == "all") {
1576 LOG(FATAL) << "Cannot retrieve a singular name when using all slots";
1577 }
1578 return entry.first->part_name + "_" + slot;
1579}
1580
Daniel Zheng29a211c2023-03-10 07:23:49 +00001581std::unique_ptr<FlashTask> ParseFlashCommand(const FlashingPlan* fp,
1582 const std::vector<std::string>& parts) {
1583 bool apply_vbmeta = false;
1584 std::string slot = fp->slot_override;
1585 std::string partition;
1586 std::string img_name;
1587 for (auto& part : parts) {
1588 if (part == "--apply-vbmeta") {
1589 apply_vbmeta = true;
1590 } else if (part == "--slot-other") {
1591 slot = fp->secondary_slot;
1592 } else if (partition.empty()) {
1593 partition = part;
1594 } else if (img_name.empty()) {
1595 img_name = part;
1596 } else {
1597 LOG(ERROR) << "unknown argument" << part
1598 << " in fastboot-info.txt. parts: " << android::base::Join(parts, " ");
1599 return nullptr;
1600 }
1601 }
1602 if (partition.empty()) {
1603 LOG(ERROR) << "partition name not found when parsing fastboot-info.txt. parts: "
1604 << android::base::Join(parts, " ");
1605 return nullptr;
1606 }
1607 if (img_name.empty()) {
1608 img_name = partition + ".img";
1609 }
Daniel Zheng791a83b2023-05-23 10:42:39 -07001610 return std::make_unique<FlashTask>(slot, partition, img_name, apply_vbmeta, fp);
Daniel Zheng29a211c2023-03-10 07:23:49 +00001611}
1612
1613std::unique_ptr<RebootTask> ParseRebootCommand(const FlashingPlan* fp,
1614 const std::vector<std::string>& parts) {
1615 if (parts.empty()) return std::make_unique<RebootTask>(fp);
1616 if (parts.size() > 1) {
1617 LOG(ERROR) << "unknown arguments in reboot {target} in fastboot-info.txt: "
1618 << android::base::Join(parts, " ");
1619 return nullptr;
1620 }
1621 return std::make_unique<RebootTask>(fp, parts[0]);
1622}
1623
1624std::unique_ptr<WipeTask> ParseWipeCommand(const FlashingPlan* fp,
1625 const std::vector<std::string>& parts) {
1626 if (parts.size() != 1) {
1627 LOG(ERROR) << "unknown arguments in erase {partition} in fastboot-info.txt: "
1628 << android::base::Join(parts, " ");
1629 return nullptr;
1630 }
1631 return std::make_unique<WipeTask>(fp, parts[0]);
1632}
1633
1634std::unique_ptr<Task> ParseFastbootInfoLine(const FlashingPlan* fp,
1635 const std::vector<std::string>& command) {
1636 if (command.size() == 0) {
1637 return nullptr;
1638 }
1639 std::unique_ptr<Task> task;
1640
1641 if (command[0] == "flash") {
1642 task = ParseFlashCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
1643 } else if (command[0] == "reboot") {
1644 task = ParseRebootCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
1645 } else if (command[0] == "update-super" && command.size() == 1) {
1646 task = std::make_unique<UpdateSuperTask>(fp);
1647 } else if (command[0] == "erase" && command.size() == 2) {
1648 task = ParseWipeCommand(fp, std::vector<std::string>{command.begin() + 1, command.end()});
1649 }
1650 if (!task) {
1651 LOG(ERROR) << "unknown command parsing fastboot-info.txt line: "
1652 << android::base::Join(command, " ");
1653 }
1654 return task;
1655}
1656
Daniel Zheng997ce152023-05-30 09:24:46 -07001657bool AddResizeTasks(const FlashingPlan* fp, std::vector<std::unique_ptr<Task>>* tasks) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001658 // expands "resize-partitions" into individual commands : resize {os_partition_1}, resize
1659 // {os_partition_2}, etc.
1660 std::vector<std::unique_ptr<Task>> resize_tasks;
1661 std::optional<size_t> loc;
Daniel Zheng997ce152023-05-30 09:24:46 -07001662 std::vector<char> contents;
1663 if (!fp->source->ReadFile("super_empty.img", &contents)) {
1664 return false;
1665 }
1666 auto metadata = android::fs_mgr::ReadFromImageBlob(contents.data(), contents.size());
1667 if (!metadata) {
1668 return false;
1669 }
Daniel Zheng29a211c2023-03-10 07:23:49 +00001670 for (size_t i = 0; i < tasks->size(); i++) {
1671 if (auto flash_task = tasks->at(i)->AsFlashTask()) {
Daniel Zheng997ce152023-05-30 09:24:46 -07001672 if (should_flash_in_userspace(*metadata.get(), flash_task->GetPartitionAndSlot())) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001673 if (!loc) {
1674 loc = i;
1675 }
1676 resize_tasks.emplace_back(std::make_unique<ResizeTask>(
1677 fp, flash_task->GetPartition(), "0", fp->slot_override));
1678 }
1679 }
1680 }
1681 // if no logical partitions (although should never happen since system will always need to be
1682 // flashed)
1683 if (!loc) {
Daniel Zheng997ce152023-05-30 09:24:46 -07001684 return false;
Daniel Zheng29a211c2023-03-10 07:23:49 +00001685 }
1686 tasks->insert(tasks->begin() + loc.value(), std::make_move_iterator(resize_tasks.begin()),
1687 std::make_move_iterator(resize_tasks.end()));
Daniel Zheng997ce152023-05-30 09:24:46 -07001688 return true;
Daniel Zheng29a211c2023-03-10 07:23:49 +00001689}
1690
Daniel Zheng29a211c2023-03-10 07:23:49 +00001691static bool IsIgnore(const std::vector<std::string>& command) {
Daniel Zheng791a83b2023-05-23 10:42:39 -07001692 if (command.size() == 0 || command[0][0] == '#') {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001693 return true;
1694 }
1695 return false;
1696}
1697
Daniel Zheng630f29e2023-04-28 14:06:45 -07001698bool CheckFastbootInfoRequirements(const std::vector<std::string>& command,
1699 uint32_t host_tool_version) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001700 if (command.size() != 2) {
1701 LOG(ERROR) << "unknown characters in version info in fastboot-info.txt -> "
1702 << android::base::Join(command, " ");
1703 return false;
1704 }
1705 if (command[0] != "version") {
1706 LOG(ERROR) << "unknown characters in version info in fastboot-info.txt -> "
1707 << android::base::Join(command, " ");
1708 return false;
1709 }
1710
Daniel Zheng630f29e2023-04-28 14:06:45 -07001711 uint32_t fastboot_info_version;
1712 if (!android::base::ParseUint(command[1], &fastboot_info_version)) {
1713 LOG(ERROR) << "version number contains non-numeric characters in fastboot-info.txt -> "
Daniel Zheng29a211c2023-03-10 07:23:49 +00001714 << android::base::Join(command, " ");
1715 return false;
1716 }
1717
1718 LOG(VERBOSE) << "Checking 'fastboot-info.txt version'";
Daniel Zheng630f29e2023-04-28 14:06:45 -07001719 if (fastboot_info_version <= host_tool_version) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001720 return true;
1721 }
Daniel Zheng630f29e2023-04-28 14:06:45 -07001722
Daniel Zheng29a211c2023-03-10 07:23:49 +00001723 LOG(ERROR) << "fasboot-info.txt version: " << command[1]
Daniel Zheng630f29e2023-04-28 14:06:45 -07001724 << " not compatible with host tool version --> " << host_tool_version;
Daniel Zheng29a211c2023-03-10 07:23:49 +00001725 return false;
1726}
1727
1728std::vector<std::unique_ptr<Task>> ParseFastbootInfo(const FlashingPlan* fp,
1729 const std::vector<std::string>& file) {
1730 std::vector<std::unique_ptr<Task>> tasks;
1731 // Get os_partitions that need to be resized
1732 for (auto& text : file) {
1733 std::vector<std::string> command = android::base::Tokenize(text, " ");
1734 if (IsIgnore(command)) {
1735 continue;
1736 }
1737 if (command.size() > 1 && command[0] == "version") {
Daniel Zheng451e46f2023-04-28 16:37:46 -07001738 if (!CheckFastbootInfoRequirements(command, FASTBOOT_INFO_VERSION)) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001739 return {};
1740 }
1741 continue;
1742 } else if (command.size() >= 2 && command[0] == "if-wipe") {
1743 if (!fp->wants_wipe) {
1744 continue;
1745 }
1746 command.erase(command.begin());
1747 }
1748 auto task = ParseFastbootInfoLine(fp, command);
1749 if (!task) {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001750 return {};
1751 }
1752 tasks.emplace_back(std::move(task));
1753 }
1754 if (auto flash_super_task = FlashSuperLayoutTask::InitializeFromTasks(fp, tasks)) {
1755 auto it = tasks.begin();
1756 for (size_t i = 0; i < tasks.size(); i++) {
1757 if (auto flash_task = tasks[i]->AsFlashTask()) {
1758 if (should_flash_in_userspace(flash_task->GetPartitionAndSlot())) {
1759 break;
1760 }
1761 }
1762 if (auto wipe_task = tasks[i]->AsWipeTask()) {
1763 break;
1764 }
1765 it++;
1766 }
1767 tasks.insert(it, std::move(flash_super_task));
1768 } else {
Daniel Zheng997ce152023-05-30 09:24:46 -07001769 if (!AddResizeTasks(fp, &tasks)) {
1770 LOG(WARNING) << "Failed to add resize tasks";
1771 };
Daniel Zheng29a211c2023-03-10 07:23:49 +00001772 }
1773 return tasks;
1774}
1775
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001776FlashAllTool::FlashAllTool(FlashingPlan* fp) : fp_(fp) {}
David Anderson32e376f2018-08-16 13:43:11 -07001777
David Andersoncf444f32018-08-29 14:15:49 -07001778void FlashAllTool::Flash() {
Tom Cherry9027af02018-09-24 15:48:09 -07001779 DumpInfo();
David Andersoncf444f32018-08-29 14:15:49 -07001780 CheckRequirements();
David Anderson96a9fd42018-11-05 15:21:44 -08001781
1782 // Change the slot first, so we boot into the correct recovery image when
1783 // using fastbootd.
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001784 if (fp_->slot_override == "all") {
David Anderson96a9fd42018-11-05 15:21:44 -08001785 set_active("a");
1786 } else {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001787 set_active(fp_->slot_override);
David Anderson96a9fd42018-11-05 15:21:44 -08001788 }
1789
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001790 DetermineSlot();
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001791
David Andersonab8f4662019-10-21 16:45:59 -07001792 CancelSnapshotIfNeeded();
1793
Daniel Zhengba07ef52023-06-21 14:14:19 -07001794 tasks_ = CollectTasksFromImageList();
1795 for (auto& task : tasks_) {
1796 task->Run();
1797 }
Daniel Zheng2a565922023-05-31 11:20:08 -07001798 return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001799}
1800
David Andersoncf444f32018-08-29 14:15:49 -07001801void FlashAllTool::CheckRequirements() {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001802 std::vector<char> contents;
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001803 if (!fp_->source->ReadFile("android-info.txt", &contents)) {
David Andersoncf444f32018-08-29 14:15:49 -07001804 die("could not read android-info.txt");
1805 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001806 ::CheckRequirements({contents.data(), contents.size()}, fp_->force_flash);
David Andersoncf444f32018-08-29 14:15:49 -07001807}
1808
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001809void FlashAllTool::DetermineSlot() {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001810 if (fp_->slot_override.empty()) {
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001811 fp_->current_slot = get_current_slot();
1812 } else {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001813 fp_->current_slot = fp_->slot_override;
Kelvin Zhang2a4a45f2023-04-03 20:44:05 +00001814 }
1815
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001816 if (fp_->skip_secondary) {
David Andersoncf444f32018-08-29 14:15:49 -07001817 return;
1818 }
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001819 if (fp_->slot_override != "" && fp_->slot_override != "all") {
1820 fp_->secondary_slot = get_other_slot(fp_->slot_override);
David Andersoncf444f32018-08-29 14:15:49 -07001821 } else {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001822 fp_->secondary_slot = get_other_slot();
David Andersoncf444f32018-08-29 14:15:49 -07001823 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001824 if (fp_->secondary_slot == "") {
David Andersoncf444f32018-08-29 14:15:49 -07001825 if (supports_AB()) {
1826 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1827 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001828 fp_->skip_secondary = true;
David Andersoncf444f32018-08-29 14:15:49 -07001829 }
1830}
1831
1832void FlashAllTool::CollectImages() {
Daniel Zheng65452d02022-11-30 02:25:31 +00001833 for (size_t i = 0; i < images.size(); ++i) {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07001834 std::string slot = fp_->slot_override;
David Andersoncf444f32018-08-29 14:15:49 -07001835 if (images[i].IsSecondary()) {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001836 if (fp_->skip_secondary) {
David Andersoncf444f32018-08-29 14:15:49 -07001837 continue;
1838 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001839 slot = fp_->secondary_slot;
David Andersoncf444f32018-08-29 14:15:49 -07001840 }
1841 if (images[i].type == ImageType::BootCritical) {
1842 boot_images_.emplace_back(&images[i], slot);
1843 } else if (images[i].type == ImageType::Normal) {
1844 os_images_.emplace_back(&images[i], slot);
1845 }
1846 }
1847}
1848
Daniel Zhengba07ef52023-06-21 14:14:19 -07001849std::vector<std::unique_ptr<Task>> FlashAllTool::CollectTasksFromImageList() {
Daniel Zheng29a211c2023-03-10 07:23:49 +00001850 CollectImages();
1851 // First flash boot partitions. We allow this to happen either in userspace
1852 // or in bootloader fastboot.
Daniel Zheng29a211c2023-03-10 07:23:49 +00001853 std::vector<std::unique_ptr<Task>> tasks;
Daniel Zhengba07ef52023-06-21 14:14:19 -07001854 AddFlashTasks(boot_images_, tasks);
Daniel Zheng29a211c2023-03-10 07:23:49 +00001855
1856 if (auto flash_super_task = FlashSuperLayoutTask::Initialize(fp_, os_images_)) {
1857 tasks.emplace_back(std::move(flash_super_task));
1858 } else {
1859 // Sync the super partition. This will reboot to userspace fastboot if needed.
1860 tasks.emplace_back(std::make_unique<UpdateSuperTask>(fp_));
1861 // Resize any logical partition to 0, so each partition is reset to 0
1862 // extents, and will achieve more optimal allocation.
1863 for (const auto& [image, slot] : os_images_) {
1864 // Retrofit devices have two super partitions, named super_a and super_b.
1865 // On these devices, secondary slots must be flashed as physical
1866 // partitions (otherwise they would not mount on first boot). To enforce
1867 // this, we delete any logical partitions for the "other" slot.
1868 if (is_retrofit_device()) {
1869 std::string partition_name = image->part_name + "_"s + slot;
1870 if (image->IsSecondary() && should_flash_in_userspace(partition_name)) {
1871 fp_->fb->DeletePartition(partition_name);
1872 }
1873 tasks.emplace_back(std::make_unique<DeleteTask>(fp_, partition_name));
1874 }
1875 tasks.emplace_back(std::make_unique<ResizeTask>(fp_, image->part_name, "0", slot));
1876 }
1877 }
Daniel Zhengba07ef52023-06-21 14:14:19 -07001878 AddFlashTasks(os_images_, tasks);
1879 return tasks;
Daniel Zheng29a211c2023-03-10 07:23:49 +00001880}
1881
Daniel Zhengba07ef52023-06-21 14:14:19 -07001882void FlashAllTool::AddFlashTasks(const std::vector<std::pair<const Image*, std::string>>& images,
1883 std::vector<std::unique_ptr<Task>>& tasks) {
David Andersoncf444f32018-08-29 14:15:49 -07001884 for (const auto& [image, slot] : images) {
1885 fastboot_buffer buf;
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001886 unique_fd fd = fp_->source->OpenFile(image->img_name);
Daniel Zheng5769b262023-06-21 14:41:11 -07001887 if (fd < 0 || !load_buf_fd(std::move(fd), &buf, fp_)) {
David Andersoncf444f32018-08-29 14:15:49 -07001888 if (image->optional_if_no_image) {
1889 continue;
1890 }
Daniel Zheng65452d02022-11-30 02:25:31 +00001891 die("could not load '%s': %s", image->img_name.c_str(), strerror(errno));
David Andersoncf444f32018-08-29 14:15:49 -07001892 }
Daniel Zhengba07ef52023-06-21 14:14:19 -07001893 tasks.emplace_back(std::make_unique<FlashTask>(slot, image->part_name, image->img_name,
1894 is_vbmeta_partition(image->part_name), fp_));
David Andersoncf444f32018-08-29 14:15:49 -07001895 }
1896}
1897
Tom Cherrydfd85df2018-09-20 14:45:05 -07001898bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1899 return UnzipToMemory(zip_, name, out);
David Andersoncf444f32018-08-29 14:15:49 -07001900}
1901
Yifan Hongb10d0672021-02-22 15:06:27 -08001902unique_fd ZipImageSource::OpenFile(const std::string& name) const {
Daniel Zheng30e648b2023-05-25 15:56:29 -07001903 return UnzipToFile(zip_, name.c_str());
David Andersoncf444f32018-08-29 14:15:49 -07001904}
1905
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001906static void do_update(const char* filename, FlashingPlan* fp) {
David Andersoncf444f32018-08-29 14:15:49 -07001907 ZipArchiveHandle zip;
1908 int error = OpenArchive(filename, &zip);
1909 if (error != 0) {
1910 die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1911 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001912 ZipImageSource zp = ZipImageSource(zip);
1913 fp->source = &zp;
1914 fp->wants_wipe = false;
1915 FlashAllTool tool(fp);
David Andersoncf444f32018-08-29 14:15:49 -07001916 tool.Flash();
1917
1918 CloseArchive(zip);
1919}
1920
Tom Cherrydfd85df2018-09-20 14:45:05 -07001921bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
David Andersoncf444f32018-08-29 14:15:49 -07001922 auto path = find_item_given_name(name);
1923 if (path.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001924 return false;
David Andersoncf444f32018-08-29 14:15:49 -07001925 }
Tom Cherrydfd85df2018-09-20 14:45:05 -07001926 return ReadFileToVector(path, out);
David Andersoncf444f32018-08-29 14:15:49 -07001927}
1928
Yifan Hongb10d0672021-02-22 15:06:27 -08001929unique_fd LocalImageSource::OpenFile(const std::string& name) const {
David Andersoncf444f32018-08-29 14:15:49 -07001930 auto path = find_item_given_name(name);
Yifan Hongb10d0672021-02-22 15:06:27 -08001931 return unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_BINARY)));
David Andersoncf444f32018-08-29 14:15:49 -07001932}
1933
Daniel Zheng7df2ab92023-02-21 18:22:08 +00001934static void do_flashall(FlashingPlan* fp) {
1935 LocalImageSource s = LocalImageSource();
1936 fp->source = &s;
1937 FlashAllTool tool(fp);
David Andersoncf444f32018-08-29 14:15:49 -07001938 tool.Flash();
1939}
1940
Elliott Hughesd6365a72017-05-08 18:04:49 -07001941static std::string next_arg(std::vector<std::string>* args) {
1942 if (args->empty()) syntax_error("expected argument");
1943 std::string result = args->front();
1944 args->erase(args->begin());
1945 return result;
Patrick Tjin51e8b032015-09-01 08:15:23 -07001946}
1947
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001948static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001949 if (args->empty()) syntax_error("empty oem command");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001950
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001951 std::string command(cmd);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001952 while (!args->empty()) {
Elliott Hughes29d5d7d2017-05-11 15:05:13 -07001953 command += " " + next_arg(args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001954 }
Tom Cherry9027af02018-09-24 15:48:09 -07001955 fb->RawCommand(command, "");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001956}
1957
Aaron Wisnerdb511202018-06-26 15:38:35 -05001958static unsigned fb_get_flash_block_size(std::string name) {
Connor O'Brience16a8a2017-02-06 14:39:31 -08001959 std::string sizeString;
Tom Cherry9027af02018-09-24 15:48:09 -07001960 if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001961 // This device does not report flash block sizes, so return 0.
Connor O'Brience16a8a2017-02-06 14:39:31 -08001962 return 0;
1963 }
1964 sizeString = fb_fix_numeric_var(sizeString);
1965
1966 unsigned size;
1967 if (!android::base::ParseUint(sizeString, &size)) {
1968 fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1969 return 0;
1970 }
Connor O'Brien6ef5c242017-11-01 17:37:32 -07001971 if ((size & (size - 1)) != 0) {
1972 fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
Connor O'Brience16a8a2017-02-06 14:39:31 -08001973 return 0;
1974 }
1975 return size;
1976}
1977
Daniel Zheng15e77832023-03-13 17:09:43 +00001978void fb_perform_format(const std::string& partition, int skip_if_not_supported,
1979 const std::string& type_override, const std::string& size_override,
Daniel Zheng5769b262023-06-21 14:41:11 -07001980 const unsigned fs_options, const FlashingPlan* fp) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001981 std::string partition_type, partition_size;
1982
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001983 struct fastboot_buffer buf;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001984 const char* errMsg = nullptr;
1985 const struct fs_generator* gen = nullptr;
Jin Qian4a335822017-04-18 16:23:18 -07001986 TemporaryFile output;
1987 unique_fd fd;
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001988
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001989 unsigned int limit = INT_MAX;
1990 if (target_sparse_limit > 0 && target_sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001991 limit = target_sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001992 }
Daniel Zheng5769b262023-06-21 14:41:11 -07001993 if (fp->sparse_limit > 0 && fp->sparse_limit < limit) {
1994 limit = fp->sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001995 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001996
Tom Cherry9027af02018-09-24 15:48:09 -07001997 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001998 errMsg = "Can't determine partition type.\n";
1999 goto failed;
2000 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002001 if (!type_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002002 if (partition_type != type_override) {
2003 fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07002004 partition.c_str(), partition_type.c_str(), type_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07002005 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002006 partition_type = type_override;
JP Abgrall7e859742014-05-06 15:14:15 -07002007 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002008
Tom Cherry9027af02018-09-24 15:48:09 -07002009 if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002010 errMsg = "Unable to get partition size\n";
2011 goto failed;
2012 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002013 if (!size_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002014 if (partition_size != size_override) {
2015 fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07002016 partition.c_str(), partition_size.c_str(), size_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07002017 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002018 partition_size = size_override;
JP Abgrall7e859742014-05-06 15:14:15 -07002019 }
Connor O'Brience16a8a2017-02-06 14:39:31 -08002020 partition_size = fb_fix_numeric_var(partition_size);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002021
Elliott Hughes8ab9a322015-11-02 14:05:57 -08002022 gen = fs_get_generator(partition_type);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002023 if (!gen) {
2024 if (skip_if_not_supported) {
2025 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002026 fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002027 return;
2028 }
Daniel Zheng65452d02022-11-30 02:25:31 +00002029 die("Formatting is not supported for file system with type '%s'.", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002030 }
2031
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002032 int64_t size;
Elliott Hughesda46b392016-10-11 17:09:00 -07002033 if (!android::base::ParseInt(partition_size, &size)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08002034 die("Couldn't parse partition size '%s'.", partition_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002035 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002036
Connor O'Brience16a8a2017-02-06 14:39:31 -08002037 unsigned eraseBlkSize, logicalBlkSize;
Aaron Wisnerdb511202018-06-26 15:38:35 -05002038 eraseBlkSize = fb_get_flash_block_size("erase-block-size");
2039 logicalBlkSize = fb_get_flash_block_size("logical-block-size");
Connor O'Brience16a8a2017-02-06 14:39:31 -08002040
Thiébaud Weksteen5d72d6c2022-07-21 14:43:20 +10002041 if (fs_generator_generate(gen, output.path, size, eraseBlkSize, logicalBlkSize, fs_options)) {
Elliott Hughes5620d222018-03-28 08:20:00 -07002042 die("Cannot generate image for %s", partition.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002043 }
2044
Jin Qian4a335822017-04-18 16:23:18 -07002045 fd.reset(open(output.path, O_RDONLY));
2046 if (fd == -1) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08002047 die("Cannot open generated image: %s", strerror(errno));
Jin Qian4a335822017-04-18 16:23:18 -07002048 }
Daniel Zheng5769b262023-06-21 14:41:11 -07002049 if (!load_buf_fd(std::move(fd), &buf, fp)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08002050 die("Cannot read image: %s", strerror(errno));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002051 }
Daniel Zheng403657d2023-03-10 07:37:25 +00002052 flash_buf(partition, &buf, is_vbmeta_partition(partition));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002053 return;
2054
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002055failed:
2056 if (skip_if_not_supported) {
2057 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002058 if (errMsg) fprintf(stderr, "%s", errMsg);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002059 }
Tom Cherry9027af02018-09-24 15:48:09 -07002060 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
Mark Salyzyna30b6962018-11-20 11:04:15 -08002061 if (!skip_if_not_supported) {
2062 die("Command failed");
2063 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07002064}
2065
Daniel Zheng0d307182023-01-31 21:07:53 +00002066bool should_flash_in_userspace(const std::string& partition_name) {
David Andersone0e693c2018-11-27 20:19:26 -08002067 if (!get_android_product_out()) {
2068 return false;
2069 }
David Anderson89569642018-11-16 15:53:35 -08002070 auto path = find_item_given_name("super_empty.img");
David Anderson00475802018-12-04 17:05:47 -08002071 if (path.empty() || access(path.c_str(), R_OK)) {
David Anderson89569642018-11-16 15:53:35 -08002072 return false;
2073 }
2074 auto metadata = android::fs_mgr::ReadFromImageFile(path);
2075 if (!metadata) {
2076 return false;
2077 }
David Andersonaa87dc52023-01-27 20:39:06 -08002078 return should_flash_in_userspace(*metadata.get(), partition_name);
David Anderson89569642018-11-16 15:53:35 -08002079}
2080
David Anderson7c84b9f2019-06-27 22:15:29 -07002081static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
Daniel Zheng791a83b2023-05-23 10:42:39 -07002082 std::string* message, const FlashingPlan* fp) {
David Anderson7c84b9f2019-06-27 22:15:29 -07002083 auto super_device = GetMetadataSuperBlockDevice(metadata);
2084 auto block_size = metadata.geometry.logical_block_size;
2085 auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
2086
2087 if (super_bdev_name != "super") {
2088 // retrofit devices do not allow flashing to the retrofit partitions,
2089 // so enable it if we can.
2090 fb->RawCommand("oem allow-flash-super");
2091 }
2092
2093 // Note: do not use die() in here, since we want TemporaryDir's destructor
2094 // to be called.
2095 TemporaryDir temp_dir;
2096
2097 bool ok;
2098 if (metadata.block_devices.size() > 1) {
2099 ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
2100 } else {
2101 auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
2102 ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
2103 }
2104 if (!ok) {
2105 *message = "Could not generate a flashable super image file";
2106 return false;
2107 }
2108
2109 for (const auto& block_device : metadata.block_devices) {
2110 auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
2111 bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
2112
2113 std::string image_name;
2114 if (metadata.block_devices.size() > 1) {
2115 image_name = "super_" + partition + ".img";
2116 } else {
2117 image_name = partition + ".img";
2118 }
2119
2120 auto image_path = temp_dir.path + "/"s + image_name;
2121 auto flash = [&](const std::string& partition_name) {
Daniel Zheng791a83b2023-05-23 10:42:39 -07002122 do_flash(partition_name.c_str(), image_path.c_str(), false, fp);
David Anderson7c84b9f2019-06-27 22:15:29 -07002123 };
2124 do_for_partitions(partition, slot, flash, force_slot);
2125
2126 unlink(image_path.c_str());
2127 }
2128 return true;
2129}
2130
Daniel Zheng791a83b2023-05-23 10:42:39 -07002131static void do_wipe_super(const std::string& image, const std::string& slot_override,
2132 const FlashingPlan* fp) {
David Anderson7c84b9f2019-06-27 22:15:29 -07002133 if (access(image.c_str(), R_OK) != 0) {
2134 die("Could not read image: %s", image.c_str());
2135 }
2136 auto metadata = android::fs_mgr::ReadFromImageFile(image);
2137 if (!metadata) {
2138 die("Could not parse image: %s", image.c_str());
2139 }
2140
2141 auto slot = slot_override;
2142 if (slot.empty()) {
2143 slot = get_current_slot();
2144 }
2145
2146 std::string message;
Daniel Zheng791a83b2023-05-23 10:42:39 -07002147 if (!wipe_super(*metadata.get(), slot, &message, fp)) {
David Anderson7c84b9f2019-06-27 22:15:29 -07002148 die(message);
2149 }
2150}
2151
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +00002152static void FastbootLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
David Andersona67fc322023-01-27 16:15:52 -08002153 const char* /* tag */, const char* /* file */, unsigned int /* line */,
2154 const char* message) {
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +00002155 switch (severity) {
2156 case android::base::INFO:
2157 fprintf(stdout, "%s\n", message);
2158 break;
2159 case android::base::ERROR:
2160 fprintf(stderr, "%s\n", message);
2161 break;
2162 default:
2163 verbose("%s\n", message);
2164 }
David Andersona67fc322023-01-27 16:15:52 -08002165}
2166
2167static void FastbootAborter(const char* message) {
2168 die("%s", message);
2169}
2170
Aaron Wisnerdb511202018-06-26 15:38:35 -05002171int FastBootTool::Main(int argc, char* argv[]) {
David Andersona67fc322023-01-27 16:15:52 -08002172 android::base::InitLogging(argv, FastbootLogger, FastbootAborter);
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002173 std::unique_ptr<FlashingPlan> fp = std::make_unique<FlashingPlan>();
David Andersona67fc322023-01-27 16:15:52 -08002174
Florian Bäuerle27ded482014-11-24 11:29:34 +01002175 int longindex;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002176 std::string next_active;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002177
Elliott Hughes577e8b42018-04-05 16:12:47 -07002178 g_boot_img_hdr.kernel_addr = 0x00008000;
2179 g_boot_img_hdr.ramdisk_addr = 0x01000000;
2180 g_boot_img_hdr.second_addr = 0x00f00000;
2181 g_boot_img_hdr.tags_addr = 0x00000100;
2182 g_boot_img_hdr.page_size = 2048;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08002183 g_boot_img_hdr.dtb_addr = 0x01100000;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002184
Daniel Zheng65452d02022-11-30 02:25:31 +00002185 const struct option longopts[] = {{"base", required_argument, 0, 0},
2186 {"cmdline", required_argument, 0, 0},
2187 {"disable-verification", no_argument, 0, 0},
2188 {"disable-verity", no_argument, 0, 0},
Daniel Zhengd62002c2023-06-21 14:27:35 -07002189 {"disable-super-optimization", no_argument, 0, 0},
Daniel Zheng65452d02022-11-30 02:25:31 +00002190 {"force", no_argument, 0, 0},
2191 {"fs-options", required_argument, 0, 0},
2192 {"header-version", required_argument, 0, 0},
2193 {"help", no_argument, 0, 'h'},
2194 {"kernel-offset", required_argument, 0, 0},
2195 {"os-patch-level", required_argument, 0, 0},
2196 {"os-version", required_argument, 0, 0},
2197 {"page-size", required_argument, 0, 0},
2198 {"ramdisk-offset", required_argument, 0, 0},
2199 {"set-active", optional_argument, 0, 'a'},
2200 {"skip-reboot", no_argument, 0, 0},
2201 {"skip-secondary", no_argument, 0, 0},
2202 {"slot", required_argument, 0, 0},
2203 {"tags-offset", required_argument, 0, 0},
2204 {"dtb", required_argument, 0, 0},
2205 {"dtb-offset", required_argument, 0, 0},
2206 {"unbuffered", no_argument, 0, 0},
2207 {"verbose", no_argument, 0, 'v'},
2208 {"version", no_argument, 0, 0},
2209 {0, 0, 0, 0}};
Colin Cross8879f982012-05-22 17:53:34 -07002210
John Stultz9d2fb9c2023-06-09 18:52:22 +00002211 serial = getenv("FASTBOOT_DEVICE");
2212 if (!serial)
2213 serial = getenv("ANDROID_SERIAL");
Colin Cross8879f982012-05-22 17:53:34 -07002214
Elliott Hughes577e8b42018-04-05 16:12:47 -07002215 int c;
Elliott Hughesf3192bd2018-04-10 15:38:08 -07002216 while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
Elliott Hughes577e8b42018-04-05 16:12:47 -07002217 if (c == 0) {
2218 std::string name{longopts[longindex].name};
2219 if (name == "base") {
2220 g_base_addr = strtoul(optarg, 0, 16);
2221 } else if (name == "cmdline") {
2222 g_cmdline = optarg;
2223 } else if (name == "disable-verification") {
2224 g_disable_verification = true;
2225 } else if (name == "disable-verity") {
2226 g_disable_verity = true;
Daniel Zhengd62002c2023-06-21 14:27:35 -07002227 } else if (name == "disable-super-optimization") {
2228 fp->should_optimize_flash_super = false;
David Anderson89569642018-11-16 15:53:35 -08002229 } else if (name == "force") {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002230 fp->force_flash = true;
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002231 } else if (name == "fs-options") {
Daniel Zheng15e77832023-03-13 17:09:43 +00002232 fp->fs_options = ParseFsOption(optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002233 } else if (name == "header-version") {
2234 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08002235 } else if (name == "dtb") {
2236 g_dtb_path = optarg;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002237 } else if (name == "kernel-offset") {
2238 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
2239 } else if (name == "os-patch-level") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002240 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002241 } else if (name == "os-version") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002242 ParseOsVersion(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002243 } else if (name == "page-size") {
2244 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
2245 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
2246 } else if (name == "ramdisk-offset") {
2247 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
2248 } else if (name == "skip-reboot") {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002249 fp->skip_reboot = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002250 } else if (name == "skip-secondary") {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002251 fp->skip_secondary = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002252 } else if (name == "slot") {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002253 fp->slot_override = optarg;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08002254 } else if (name == "dtb-offset") {
2255 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002256 } else if (name == "tags-offset") {
2257 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
2258 } else if (name == "unbuffered") {
Elliott Hughesfc797672015-04-07 20:12:50 -07002259 setvbuf(stdout, nullptr, _IONBF, 0);
2260 setvbuf(stderr, nullptr, _IONBF, 0);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002261 } else if (name == "version") {
Daniel Zheng65452d02022-11-30 02:25:31 +00002262 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION,
2263 android::build::GetBuildNumber().c_str());
Elliott Hughes1fd46df2017-03-30 15:08:28 -07002264 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
Elliott Hughes379646b2015-06-02 13:50:00 -07002265 return 0;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00002266 } else {
Elliott Hughes855cdf82018-04-02 14:24:03 -07002267 die("unknown option %s", longopts[longindex].name);
Florian Bäuerle27ded482014-11-24 11:29:34 +01002268 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07002269 } else {
2270 switch (c) {
2271 case 'a':
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002272 fp->wants_set_active = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002273 if (optarg) next_active = optarg;
2274 break;
2275 case 'h':
2276 return show_help();
Elliott Hughes577e8b42018-04-05 16:12:47 -07002277 case 'l':
2278 g_long_listing = true;
2279 break;
2280 case 's':
2281 serial = optarg;
2282 break;
2283 case 'S':
Daniel Zheng5769b262023-06-21 14:41:11 -07002284 if (!android::base::ParseByteCount(optarg, &fp->sparse_limit)) {
Elliott Hughes542370d2018-04-19 19:49:44 -07002285 die("invalid sparse limit %s", optarg);
2286 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07002287 break;
2288 case 'v':
2289 set_verbose();
2290 break;
2291 case 'w':
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002292 fp->wants_wipe = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002293 break;
2294 case '?':
2295 return 1;
2296 default:
2297 abort();
2298 }
Colin Cross8879f982012-05-22 17:53:34 -07002299 }
2300 }
2301
2302 argc -= optind;
2303 argv += optind;
2304
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002305 if (argc == 0 && !fp->wants_wipe && !fp->wants_set_active) syntax_error("no command");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002306
Colin Cross8fb6e062012-07-24 16:36:41 -07002307 if (argc > 0 && !strcmp(*argv, "devices")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002308 list_devices();
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08002309 return 0;
2310 }
2311
Dmitrii Merkurev0ee285a2023-02-11 00:02:22 +00002312 if (argc > 0 && !strcmp(*argv, "connect")) {
2313 argc -= optind;
2314 argv += optind;
2315 return Connect(argc, argv);
2316 }
2317
2318 if (argc > 0 && !strcmp(*argv, "disconnect")) {
2319 argc -= optind;
2320 argv += optind;
2321 return Disconnect(argc, argv);
2322 }
2323
Colin Crossc7b75dc2012-08-29 18:17:06 -07002324 if (argc > 0 && !strcmp(*argv, "help")) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002325 return show_help();
Colin Crossc7b75dc2012-08-29 18:17:06 -07002326 }
2327
David Pursell0b156632015-10-30 11:22:01 -07002328 Transport* transport = open_device();
David Pursell2ec418a2016-01-20 08:32:08 -08002329 if (transport == nullptr) {
2330 return 1;
2331 }
Tom Cherry9027af02018-09-24 15:48:09 -07002332 fastboot::DriverCallbacks driver_callbacks = {
Daniel Zheng65452d02022-11-30 02:25:31 +00002333 .prolog = Status,
2334 .epilog = Epilog,
2335 .info = InfoMessage,
Raphael Herouart99097cc2022-12-30 11:51:54 +00002336 .text = TextMessage,
Tom Cherry9027af02018-09-24 15:48:09 -07002337 };
Raphael Herouart99097cc2022-12-30 11:51:54 +00002338
Tom Cherry9027af02018-09-24 15:48:09 -07002339 fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
2340 fb = &fastboot_driver;
Daniel Zhengbc01da52023-02-23 03:25:52 +00002341 fp->fb = &fastboot_driver;
David Pursell2ec418a2016-01-20 08:32:08 -08002342
Elliott Hughes5620d222018-03-28 08:20:00 -07002343 const double start = now();
2344
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002345 if (fp->slot_override != "") fp->slot_override = verify_slot(fp->slot_override);
Aaron Wisnerdb511202018-06-26 15:38:35 -05002346 if (next_active != "") next_active = verify_slot(next_active, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002347
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002348 if (fp->wants_set_active) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002349 if (next_active == "") {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002350 if (fp->slot_override == "") {
Daniel Rosenberg13454092016-06-27 19:43:11 -07002351 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07002352 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
LuK1337dae48ef2020-04-06 14:38:58 +02002353 if (current_slot[0] == '_') current_slot.erase(0, 1);
Aaron Wisnerdb511202018-06-26 15:38:35 -05002354 next_active = verify_slot(current_slot, false);
Daniel Rosenberg13454092016-06-27 19:43:11 -07002355 } else {
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002356 fp->wants_set_active = false;
Daniel Rosenberg13454092016-06-27 19:43:11 -07002357 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002358 } else {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002359 next_active = verify_slot(fp->slot_override, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002360 }
2361 }
2362 }
Daniel Zheng76c93432023-03-13 20:47:19 +00002363 std::vector<std::unique_ptr<Task>> tasks;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002364 std::vector<std::string> args(argv, argv + argc);
2365 while (!args.empty()) {
2366 std::string command = next_arg(&args);
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002367
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002368 if (command == FB_CMD_GETVAR) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002369 std::string variable = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002370 DisplayVarOrError(variable, variable);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002371 } else if (command == FB_CMD_ERASE) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002372 std::string partition = next_arg(&args);
2373 auto erase = [&](const std::string& partition) {
David Pursell0b156632015-10-30 11:22:01 -07002374 std::string partition_type;
Daniel Zheng65452d02022-11-30 02:25:31 +00002375 if (fb->GetVar("partition-type:" + partition, &partition_type) ==
2376 fastboot::SUCCESS &&
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002377 fs_get_generator(partition_type) != nullptr) {
2378 fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
2379 partition_type.c_str());
2380 }
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002381
Tom Cherry9027af02018-09-24 15:48:09 -07002382 fb->Erase(partition);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002383 };
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002384 do_for_partitions(partition, fp->slot_override, erase, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002385 } else if (android::base::StartsWith(command, "format")) {
2386 // Parsing for: "format[:[type][:[size]]]"
2387 // Some valid things:
2388 // - select only the size, and leave default fs type:
2389 // format::0x4000000 userdata
2390 // - default fs type and size:
2391 // format userdata
2392 // format:: userdata
2393 std::vector<std::string> pieces = android::base::Split(command, ":");
2394 std::string type_override;
2395 if (pieces.size() > 1) type_override = pieces[1].c_str();
2396 std::string size_override;
2397 if (pieces.size() > 2) size_override = pieces[2].c_str();
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002398
Elliott Hughesd6365a72017-05-08 18:04:49 -07002399 std::string partition = next_arg(&args);
2400
2401 auto format = [&](const std::string& partition) {
Daniel Zheng5769b262023-06-21 14:41:11 -07002402 fb_perform_format(partition, 0, type_override, size_override, fp->fs_options,
2403 fp.get());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002404 };
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002405 do_for_partitions(partition, fp->slot_override, format, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002406 } else if (command == "signature") {
2407 std::string filename = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002408 std::vector<char> data;
2409 if (!ReadFileToVector(filename, &data)) {
2410 die("could not load '%s': %s", filename.c_str(), strerror(errno));
2411 }
2412 if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
Tom Cherry9027af02018-09-24 15:48:09 -07002413 fb->Download("signature", data);
2414 fb->RawCommand("signature", "installing signature");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002415 } else if (command == FB_CMD_REBOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002416 if (args.size() == 1) {
Daniel Zheng71b3b432023-01-30 17:43:00 +00002417 std::string reboot_target = next_arg(&args);
Daniel Zheng76c93432023-03-13 20:47:19 +00002418 tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), reboot_target));
Daniel Zheng1418fb82023-03-13 18:13:08 +00002419 } else if (!fp->skip_reboot) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002420 tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
Elliott Hughesca85df02015-02-25 10:02:00 -08002421 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002422 if (!args.empty()) syntax_error("junk after reboot command");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002423 } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002424 tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "bootloader"));
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002425 } else if (command == FB_CMD_REBOOT_RECOVERY) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002426 tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "recovery"));
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002427 } else if (command == FB_CMD_REBOOT_FASTBOOT) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002428 tasks.emplace_back(std::make_unique<RebootTask>(fp.get(), "fastboot"));
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002429 } else if (command == FB_CMD_CONTINUE) {
Tom Cherry9027af02018-09-24 15:48:09 -07002430 fb->Continue();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002431 } else if (command == FB_CMD_BOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002432 std::string kernel = next_arg(&args);
2433 std::string ramdisk;
2434 if (!args.empty()) ramdisk = next_arg(&args);
2435 std::string second_stage;
2436 if (!args.empty()) second_stage = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002437 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
Tom Cherry9027af02018-09-24 15:48:09 -07002438 fb->Download("boot.img", data);
2439 fb->Boot();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002440 } else if (command == FB_CMD_FLASH) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002441 std::string pname = next_arg(&args);
Elliott Hughes2810d002016-04-25 14:31:18 -07002442 std::string fname;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002443 if (!args.empty()) {
2444 fname = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002445 } else {
Elliott Hughes45964a82017-05-03 22:43:23 -07002446 fname = find_item(pname);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002447 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002448 if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
Daniel Zheng403657d2023-03-10 07:37:25 +00002449
Daniel Zheng791a83b2023-05-23 10:42:39 -07002450 FlashTask task(fp->slot_override, pname, fname, is_vbmeta_partition(pname), fp.get());
Daniel Zheng0d307182023-01-31 21:07:53 +00002451 task.Run();
Elliott Hughesd6365a72017-05-08 18:04:49 -07002452 } else if (command == "flash:raw") {
2453 std::string partition = next_arg(&args);
2454 std::string kernel = next_arg(&args);
2455 std::string ramdisk;
2456 if (!args.empty()) ramdisk = next_arg(&args);
2457 std::string second_stage;
2458 if (!args.empty()) second_stage = next_arg(&args);
2459
Tom Cherrydfd85df2018-09-20 14:45:05 -07002460 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
2461 auto flashraw = [&data](const std::string& partition) {
Tom Cherry9027af02018-09-24 15:48:09 -07002462 fb->FlashPartition(partition, data);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002463 };
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002464 do_for_partitions(partition, fp->slot_override, flashraw, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002465 } else if (command == "flashall") {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002466 if (fp->slot_override == "all") {
Daniel Zheng65452d02022-11-30 02:25:31 +00002467 fprintf(stderr,
2468 "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002469 fp->skip_secondary = true;
Alex Lightbb9b8a52016-06-29 09:26:44 -07002470 }
Daniel Zheng76c93432023-03-13 20:47:19 +00002471 do_flashall(fp.get());
2472
Daniel Zheng1418fb82023-03-13 18:13:08 +00002473 if (!fp->skip_reboot) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002474 tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
Daniel Zheng1418fb82023-03-13 18:13:08 +00002475 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002476 } else if (command == "update") {
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002477 bool slot_all = (fp->slot_override == "all");
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002478 if (slot_all) {
Daniel Zheng65452d02022-11-30 02:25:31 +00002479 fprintf(stderr,
2480 "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002481 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002482 std::string filename = "update.zip";
2483 if (!args.empty()) {
2484 filename = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002485 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002486 do_update(filename.c_str(), fp.get());
Daniel Zheng1418fb82023-03-13 18:13:08 +00002487 if (!fp->skip_reboot) {
Daniel Zheng76c93432023-03-13 20:47:19 +00002488 tasks.emplace_back(std::make_unique<RebootTask>(fp.get()));
Daniel Zheng1418fb82023-03-13 18:13:08 +00002489 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002490 } else if (command == FB_CMD_SET_ACTIVE) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002491 std::string slot = verify_slot(next_arg(&args), false);
Tom Cherry9027af02018-09-24 15:48:09 -07002492 fb->SetActive(slot);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002493 } else if (command == "stage") {
2494 std::string filename = next_arg(&args);
2495
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002496 struct fastboot_buffer buf;
Daniel Zheng5769b262023-06-21 14:41:11 -07002497 if (!load_buf(filename.c_str(), &buf, fp.get()) || buf.type != FB_BUFFER_FD) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002498 die("cannot load '%s'", filename.c_str());
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002499 }
Yifan Hong58532df2021-03-22 16:39:13 -07002500 fb->Download(filename, buf.fd.get(), buf.sz);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002501 } else if (command == "get_staged") {
2502 std::string filename = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002503 fb->Upload(filename);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002504 } else if (command == FB_CMD_OEM) {
2505 do_oem_command(FB_CMD_OEM, &args);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002506 } else if (command == "flashing") {
2507 if (args.empty()) {
2508 syntax_error("missing 'flashing' command");
Daniel Zheng65452d02022-11-30 02:25:31 +00002509 } else if (args.size() == 1 &&
2510 (args[0] == "unlock" || args[0] == "lock" || args[0] == "unlock_critical" ||
2511 args[0] == "lock_critical" || args[0] == "get_unlock_ability")) {
Elliott Hughes1eec97a2017-05-15 16:53:53 -07002512 do_oem_command("flashing", &args);
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002513 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002514 syntax_error("unknown 'flashing' command %s", args[0].c_str());
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002515 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002516 } else if (command == FB_CMD_CREATE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002517 std::string partition = next_arg(&args);
2518 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002519 fb->CreatePartition(partition, size);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002520 } else if (command == FB_CMD_DELETE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002521 std::string partition = next_arg(&args);
Daniel Zheng76c93432023-03-13 20:47:19 +00002522 tasks.emplace_back(std::make_unique<DeleteTask>(fp.get(), partition));
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002523 } else if (command == FB_CMD_RESIZE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002524 std::string partition = next_arg(&args);
2525 std::string size = next_arg(&args);
Daniel Zheng9f7bf7e2023-03-03 07:16:46 +00002526 std::unique_ptr<ResizeTask> resize_task =
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002527 std::make_unique<ResizeTask>(fp.get(), partition, size, fp->slot_override);
Daniel Zheng9f7bf7e2023-03-03 07:16:46 +00002528 resize_task->Run();
David Anderson1d504e32019-01-15 14:38:20 -08002529 } else if (command == "gsi") {
David Anderson3d782d52019-01-29 13:09:49 -08002530 std::string arg = next_arg(&args);
2531 if (arg == "wipe") {
David Anderson1d504e32019-01-15 14:38:20 -08002532 fb->RawCommand("gsi:wipe", "wiping GSI");
David Anderson3d782d52019-01-29 13:09:49 -08002533 } else if (arg == "disable") {
David Anderson1d504e32019-01-15 14:38:20 -08002534 fb->RawCommand("gsi:disable", "disabling GSI");
2535 } else {
2536 syntax_error("expected 'wipe' or 'disable'");
2537 }
David Anderson7c84b9f2019-06-27 22:15:29 -07002538 } else if (command == "wipe-super") {
2539 std::string image;
2540 if (args.empty()) {
2541 image = find_item_given_name("super_empty.img");
2542 } else {
2543 image = next_arg(&args);
2544 }
Daniel Zheng791a83b2023-05-23 10:42:39 -07002545 do_wipe_super(image, fp->slot_override, fp.get());
David Andersonab8f4662019-10-21 16:45:59 -07002546 } else if (command == "snapshot-update") {
2547 std::string arg;
2548 if (!args.empty()) {
2549 arg = next_arg(&args);
2550 }
David Anderson220ddb12019-10-31 18:02:41 -07002551 if (!arg.empty() && (arg != "cancel" && arg != "merge")) {
2552 syntax_error("expected: snapshot-update [cancel|merge]");
David Andersonab8f4662019-10-21 16:45:59 -07002553 }
2554 fb->SnapshotUpdateCommand(arg);
Yifan Hongbcd27702021-02-16 19:37:32 -08002555 } else if (command == FB_CMD_FETCH) {
2556 std::string partition = next_arg(&args);
2557 std::string outfile = next_arg(&args);
Daniel Zheng1e6456b2023-04-10 09:35:48 -07002558 do_fetch(partition, fp->slot_override, outfile);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002559 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002560 syntax_error("unknown command %s", command.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002561 }
2562 }
Daniel Zheng15e77832023-03-13 17:09:43 +00002563
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002564 if (fp->wants_wipe) {
2565 if (fp->force_flash) {
David Andersonab8f4662019-10-21 16:45:59 -07002566 CancelSnapshotIfNeeded();
2567 }
Daniel Zheng303fb492023-06-05 10:30:44 -07002568 std::vector<std::unique_ptr<Task>> wipe_tasks;
Daniel Zheng65452d02022-11-30 02:25:31 +00002569 std::vector<std::string> partitions = {"userdata", "cache", "metadata"};
Paul Crowley4d170062018-04-24 17:06:30 -07002570 for (const auto& partition : partitions) {
Daniel Zheng303fb492023-06-05 10:30:44 -07002571 wipe_tasks.emplace_back(std::make_unique<WipeTask>(fp.get(), partition));
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002572 }
Daniel Zheng303fb492023-06-05 10:30:44 -07002573 tasks.insert(tasks.begin(), std::make_move_iterator(wipe_tasks.begin()),
2574 std::make_move_iterator(wipe_tasks.end()));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002575 }
Daniel Zheng7df2ab92023-02-21 18:22:08 +00002576 if (fp->wants_set_active) {
Tom Cherry9027af02018-09-24 15:48:09 -07002577 fb->SetActive(next_active);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002578 }
Daniel Zheng76c93432023-03-13 20:47:19 +00002579 for (auto& task : tasks) {
2580 task->Run();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002581 }
Elliott Hughes5620d222018-03-28 08:20:00 -07002582 fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
David Anderson03de6452018-09-04 14:32:54 -07002583
Tom Cherry9027af02018-09-24 15:48:09 -07002584 auto* old_transport = fb->set_transport(nullptr);
2585 delete old_transport;
2586
Tom Cherry11f12092018-08-29 21:36:28 -07002587 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002588}
Elliott Hughes6ebec932018-04-10 14:22:13 -07002589
Aaron Wisnerdb511202018-06-26 15:38:35 -05002590void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002591 unsigned year, month, day;
2592 if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2593 syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2594 }
2595 if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2596 if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2597 hdr->SetOsPatchLevel(year, month);
2598}
2599
Aaron Wisnerdb511202018-06-26 15:38:35 -05002600void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002601 unsigned major = 0, minor = 0, patch = 0;
2602 std::vector<std::string> versions = android::base::Split(arg, ".");
2603 if (versions.size() < 1 || versions.size() > 3 ||
2604 (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2605 (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2606 (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2607 (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2608 syntax_error("bad OS version: %s", arg);
2609 }
2610 hdr->SetOsVersion(major, minor, patch);
2611}
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002612
2613unsigned FastBootTool::ParseFsOption(const char* arg) {
2614 unsigned fsOptions = 0;
2615
2616 std::vector<std::string> options = android::base::Split(arg, ",");
Daniel Zheng65452d02022-11-30 02:25:31 +00002617 if (options.size() < 1) syntax_error("bad options: %s", arg);
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002618
2619 for (size_t i = 0; i < options.size(); ++i) {
2620 if (options[i] == "casefold")
2621 fsOptions |= (1 << FS_OPT_CASEFOLD);
2622 else if (options[i] == "projid")
2623 fsOptions |= (1 << FS_OPT_PROJID);
2624 else if (options[i] == "compress")
2625 fsOptions |= (1 << FS_OPT_COMPRESS);
2626 else
2627 syntax_error("unsupported options: %s", options[i].c_str());
2628 }
2629 return fsOptions;
2630}