blob: 8f7cceddf2c48f747f784e37c0696310e0cbd9f6 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
Tsu Chiang Chuangee520552011-02-25 18:38:53 -080012 * the documentation and/or other materials provided with the
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080013 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
Tsu Chiang Chuangee520552011-02-25 18:38:53 -080022 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Tom Cherry9027af02018-09-24 15:48:09 -070029#include "fastboot.h"
30
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070031#include <ctype.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032#include <errno.h>
33#include <fcntl.h>
Colin Cross8879f982012-05-22 17:53:34 -070034#include <getopt.h>
Ying Wangcf86e2f2014-05-15 20:06:40 -070035#include <inttypes.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070036#include <limits.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070037#include <stdint.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <sys/stat.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#include <sys/time.h>
Colin Crossf8387882012-05-24 17:18:41 -070043#include <sys/types.h>
Mark Salyzyn5957c1f2014-04-30 14:05:28 -070044#include <unistd.h>
David Pursell2ec418a2016-01-20 08:32:08 -080045
Elliott Hughes290a2282016-11-14 17:08:47 -080046#include <chrono>
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -070047#include <functional>
Tom Cherry4aa60b32018-09-05 15:11:44 -070048#include <regex>
David Anderson0c732342018-11-28 17:10:42 -080049#include <string>
Elliott Hughes290a2282016-11-14 17:08:47 -080050#include <thread>
Josh Gao9da9ac52016-01-19 14:50:18 -080051#include <utility>
52#include <vector>
Colin Crossf8387882012-05-24 17:18:41 -070053
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080054#include <android-base/endian.h>
Elliott Hughes82ff3152016-08-31 15:07:18 -070055#include <android-base/file.h>
David Andersona67fc322023-01-27 16:15:52 -080056#include <android-base/logging.h>
Elliott Hughes749ae2d2016-06-28 14:48:45 -070057#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080058#include <android-base/parseint.h>
David Pursell2ec418a2016-01-20 08:32:08 -080059#include <android-base/parsenetaddress.h>
Elliott Hughes2810d002016-04-25 14:31:18 -070060#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080061#include <android-base/strings.h>
Chris Fries0ea946c2017-04-12 10:25:57 -050062#include <android-base/unique_fd.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070063#include <build/version.h>
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +080064#include <libavb/libavb.h>
David Anderson89569642018-11-16 15:53:35 -080065#include <liblp/liblp.h>
David Anderson667b1ef2023-01-27 21:11:11 -080066#include <liblp/super_layout_builder.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070067#include <platform_tools_version.h>
Colin Crossf8387882012-05-24 17:18:41 -070068#include <sparse/sparse.h>
Elliott Hughesd30ad8a2015-03-18 23:12:44 -070069#include <ziparchive/zip_archive.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080070
Elliott Hughes253c18d2015-03-18 22:47:09 -070071#include "bootimg_utils.h"
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -070072#include "constants.h"
Elliott Hughes1b708d32015-12-11 19:07:01 -080073#include "diagnose_usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070074#include "fastboot_driver.h"
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -070075#include "fs.h"
David Anderson667b1ef2023-01-27 21:11:11 -080076#include "super_flash_helper.h"
David Pursell2ec418a2016-01-20 08:32:08 -080077#include "tcp.h"
David Pursell0b156632015-10-30 11:22:01 -070078#include "transport.h"
David Pursell4601c972016-02-05 15:35:09 -080079#include "udp.h"
David Pursell0b156632015-10-30 11:22:01 -070080#include "usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070081#include "util.h"
Yifan Honge71fe242021-02-22 15:00:15 -080082#include "vendor_boot_img_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080083
Yifan Hongbcd27702021-02-16 19:37:32 -080084using android::base::borrowed_fd;
Tom Cherrydfd85df2018-09-20 14:45:05 -070085using android::base::ReadFully;
Tom Cherry4aa60b32018-09-05 15:11:44 -070086using android::base::Split;
87using android::base::Trim;
Chris Fries0ea946c2017-04-12 10:25:57 -050088using android::base::unique_fd;
David Anderson0c732342018-11-28 17:10:42 -080089using namespace std::string_literals;
Yifan Hongbcd27702021-02-16 19:37:32 -080090using namespace std::placeholders;
Chris Fries0ea946c2017-04-12 10:25:57 -050091
David Pursell2ec418a2016-01-20 08:32:08 -080092static const char* serial = nullptr;
Elliott Hughes577e8b42018-04-05 16:12:47 -070093
Elliott Hughes577e8b42018-04-05 16:12:47 -070094static bool g_long_listing = false;
Chris Fries6a999712017-04-04 09:52:47 -050095// Don't resparse files in too-big chunks.
96// libsparse will support INT_MAX, but this results in large allocations, so
97// let's keep it at 1GB to avoid memory pressure on the host.
98static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
Elliott Hughes542370d2018-04-19 19:49:44 -070099static uint64_t sparse_limit = 0;
Colin Crossf8387882012-05-24 17:18:41 -0700100static int64_t target_sparse_limit = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800101
Elliott Hughes577e8b42018-04-05 16:12:47 -0700102static unsigned g_base_addr = 0x10000000;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800103static boot_img_hdr_v2 g_boot_img_hdr = {};
Elliott Hughes577e8b42018-04-05 16:12:47 -0700104static std::string g_cmdline;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800105static std::string g_dtb_path;
JP Abgrall7b8970c2013-03-07 17:06:41 -0800106
David Zeuthenb6ea4352017-08-07 14:29:26 -0400107static bool g_disable_verity = false;
108static bool g_disable_verification = false;
109
Tom Cherry9027af02018-09-24 15:48:09 -0700110fastboot::FastBootDriver* fb = nullptr;
111
Rom Lemarchand622810c2013-06-28 09:54:59 -0700112enum fb_buffer_type {
Chris Fries0ea946c2017-04-12 10:25:57 -0500113 FB_BUFFER_FD,
Rom Lemarchand622810c2013-06-28 09:54:59 -0700114 FB_BUFFER_SPARSE,
115};
116
117struct fastboot_buffer {
118 enum fb_buffer_type type;
David Andersona1c983e2023-01-27 11:57:27 -0800119 std::vector<SparsePtr> files;
Elliott Hughesfc797672015-04-07 20:12:50 -0700120 int64_t sz;
Yifan Hongb10d0672021-02-22 15:06:27 -0800121 unique_fd fd;
David Anderson32e376f2018-08-16 13:43:11 -0700122 int64_t image_size;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700123};
124
David Anderson0debda02018-08-28 13:54:03 -0700125enum class ImageType {
126 // Must be flashed for device to boot into the kernel.
127 BootCritical,
128 // Normal partition to be flashed during "flashall".
129 Normal,
130 // Partition that is never flashed during "flashall".
131 Extra
132};
133
David Anderson32e376f2018-08-16 13:43:11 -0700134struct Image {
Daniel Zheng65452d02022-11-30 02:25:31 +0000135 std::string nickname;
136 std::string img_name;
137 std::string sig_name;
138 std::string part_name;
Hridya Valsarajuf1f0a9c2018-08-02 10:46:21 -0700139 bool optional_if_no_image;
David Anderson0debda02018-08-28 13:54:03 -0700140 ImageType type;
Daniel Zheng65452d02022-11-30 02:25:31 +0000141 bool IsSecondary() const { return nickname.empty(); }
David Anderson32e376f2018-08-16 13:43:11 -0700142};
143
Daniel Zheng65452d02022-11-30 02:25:31 +0000144static std::vector<Image> images = {
Dario Frenic7ea1af2018-05-25 16:07:19 +0100145 // clang-format off
David Anderson0debda02018-08-28 13:54:03 -0700146 { "boot", "boot.img", "boot.sig", "boot", false, ImageType::BootCritical },
Devin Mooredd1eb872022-01-05 00:20:15 +0000147 { "init_boot",
148 "init_boot.img", "init_boot.sig",
149 "init_boot",
Devin Moore60bd33f2022-01-11 02:01:26 +0000150 true, ImageType::BootCritical },
Daniel Zheng65452d02022-11-30 02:25:31 +0000151 { "", "boot_other.img", "boot.sig", "boot", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700152 { "cache", "cache.img", "cache.sig", "cache", true, ImageType::Extra },
153 { "dtbo", "dtbo.img", "dtbo.sig", "dtbo", true, ImageType::BootCritical },
154 { "dts", "dt.img", "dt.sig", "dts", true, ImageType::BootCritical },
155 { "odm", "odm.img", "odm.sig", "odm", true, ImageType::Normal },
Yifan Hongbe78bb62020-07-15 17:07:11 -0700156 { "odm_dlkm", "odm_dlkm.img", "odm_dlkm.sig", "odm_dlkm", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700157 { "product", "product.img", "product.sig", "product", true, ImageType::Normal },
Andrew Scullbe823d72021-01-15 14:37:15 +0000158 { "pvmfw", "pvmfw.img", "pvmfw.sig", "pvmfw", true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700159 { "recovery", "recovery.img", "recovery.sig", "recovery", true, ImageType::BootCritical },
160 { "super", "super.img", "super.sig", "super", true, ImageType::Extra },
161 { "system", "system.img", "system.sig", "system", false, ImageType::Normal },
Ramji Jiyanib3ddb532021-12-06 02:28:28 +0000162 { "system_dlkm",
163 "system_dlkm.img", "system_dlkm.sig",
164 "system_dlkm",
165 true, ImageType::Normal },
Justin Yun5d0ac622019-06-26 09:18:03 +0900166 { "system_ext",
167 "system_ext.img", "system_ext.sig",
168 "system_ext",
169 true, ImageType::Normal },
Daniel Zheng65452d02022-11-30 02:25:31 +0000170 { "", "system_other.img", "system.sig", "system", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700171 { "userdata", "userdata.img", "userdata.sig", "userdata", true, ImageType::Extra },
172 { "vbmeta", "vbmeta.img", "vbmeta.sig", "vbmeta", true, ImageType::BootCritical },
David Anderson166bfef2018-10-15 14:46:59 -0700173 { "vbmeta_system",
174 "vbmeta_system.img",
175 "vbmeta_system.sig",
176 "vbmeta_system",
David Anderson1109c922018-09-17 17:32:54 -0700177 true, ImageType::BootCritical },
Bowgo Tsaia48a7832021-06-03 14:39:34 +0800178 { "vbmeta_vendor",
179 "vbmeta_vendor.img",
180 "vbmeta_vendor.sig",
181 "vbmeta_vendor",
182 true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700183 { "vendor", "vendor.img", "vendor.sig", "vendor", true, ImageType::Normal },
Steve Muckle36112432019-08-21 11:16:14 -0700184 { "vendor_boot",
185 "vendor_boot.img", "vendor_boot.sig",
186 "vendor_boot",
187 true, ImageType::BootCritical },
Yifan Hong6b1c15c2020-05-12 10:38:53 -0700188 { "vendor_dlkm",
189 "vendor_dlkm.img", "vendor_dlkm.sig",
190 "vendor_dlkm",
191 true, ImageType::Normal },
Lucas Weif0fb5dd2022-03-28 21:57:58 +0800192 { "vendor_kernel_boot",
193 "vendor_kernel_boot.img",
194 "vendor_kernel_boot.sig",
195 "vendor_kernel_boot",
196 true, ImageType::BootCritical },
Daniel Zheng65452d02022-11-30 02:25:31 +0000197 { "", "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
Dario Frenic7ea1af2018-05-25 16:07:19 +0100198 // clang-format on
Rom Lemarchand622810c2013-06-28 09:54:59 -0700199};
Brian Swetland2a63bb72009-04-28 16:05:07 -0700200
David Andersone0e693c2018-11-27 20:19:26 -0800201static char* get_android_product_out() {
Elliott Hughes45964a82017-05-03 22:43:23 -0700202 char* dir = getenv("ANDROID_PRODUCT_OUT");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700203 if (dir == nullptr || dir[0] == '\0') {
David Andersone0e693c2018-11-27 20:19:26 -0800204 return nullptr;
205 }
206 return dir;
207}
208
209static std::string find_item_given_name(const std::string& img_name) {
210 char* dir = get_android_product_out();
211 if (!dir) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700212 die("ANDROID_PRODUCT_OUT not set");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700213 }
David Anderson0debda02018-08-28 13:54:03 -0700214 return std::string(dir) + "/" + img_name;
Alex Lightbb9b8a52016-06-29 09:26:44 -0700215}
216
Elliott Hughes29d5d7d2017-05-11 15:05:13 -0700217static std::string find_item(const std::string& item) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000218 for (size_t i = 0; i < images.size(); ++i) {
219 if (!images[i].nickname.empty() && item == images[i].nickname) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700220 return find_item_given_name(images[i].img_name);
221 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222 }
223
Elliott Hughesd6365a72017-05-08 18:04:49 -0700224 fprintf(stderr, "unknown partition '%s'\n", item.c_str());
Elliott Hughes45964a82017-05-03 22:43:23 -0700225 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800226}
227
Tom Cherry9027af02018-09-24 15:48:09 -0700228double last_start_time;
229
230static void Status(const std::string& message) {
Tom Cherry2217c502020-06-10 09:29:25 -0700231 if (!message.empty()) {
232 static constexpr char kStatusFormat[] = "%-50s ";
233 fprintf(stderr, kStatusFormat, message.c_str());
234 }
Tom Cherry9027af02018-09-24 15:48:09 -0700235 last_start_time = now();
236}
237
238static void Epilog(int status) {
239 if (status) {
240 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
241 die("Command failed");
242 } else {
243 double split = now();
244 fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
245 }
246}
247
248static void InfoMessage(const std::string& info) {
249 fprintf(stderr, "(bootloader) %s\n", info.c_str());
250}
251
Tom Cherrydfd85df2018-09-20 14:45:05 -0700252bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
253 out->clear();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254
Tom Cherrydfd85df2018-09-20 14:45:05 -0700255 unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
256 if (fd == -1) {
257 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700258 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800259
Tom Cherrydfd85df2018-09-20 14:45:05 -0700260 out->resize(get_file_size(fd));
261 return ReadFully(fd, out->data(), out->size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700262}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263
Elliott Hughesfc797672015-04-07 20:12:50 -0700264static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
Elliott Hughese1746fd2015-08-10 15:30:54 -0700265 if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
266 return -1;
267 }
268
Scott Anderson13081c62012-04-06 12:39:30 -0700269 // require matching serial number or device path if requested
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270 // at the command line with the -s option.
JP Abgralla032ded2012-06-06 11:53:33 -0700271 if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
Daniel Zheng65452d02022-11-30 02:25:31 +0000272 strcmp(local_serial, info->device_path) != 0))
273 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274 return 0;
275}
276
Elliott Hughesfc797672015-04-07 20:12:50 -0700277static int match_fastboot(usb_ifc_info* info) {
JP Abgrall7b8970c2013-03-07 17:06:41 -0800278 return match_fastboot_with_serial(info, serial);
279}
280
Elliott Hughesfc797672015-04-07 20:12:50 -0700281static int list_devices_callback(usb_ifc_info* info) {
282 if (match_fastboot_with_serial(info, nullptr) == 0) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800283 std::string serial = info->serial_number;
David Anderson4e058ca2020-05-28 04:39:37 +0000284 std::string interface = info->interface;
285 if (interface.empty()) {
286 interface = "fastboot";
287 }
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700288 if (!info->writable) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800289 serial = UsbNoPermissionsShortHelpText();
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700290 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800291 if (!serial[0]) {
292 serial = "????????????";
293 }
Scott Anderson866b1bd2012-06-04 20:29:11 -0700294 // output compatible with "adb devices"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700295 if (!g_long_listing) {
David Anderson4e058ca2020-05-28 04:39:37 +0000296 printf("%s\t%s", serial.c_str(), interface.c_str());
Scott Anderson13081c62012-04-06 12:39:30 -0700297 } else {
David Anderson4e058ca2020-05-28 04:39:37 +0000298 printf("%-22s %s", serial.c_str(), interface.c_str());
Elliott Hughes1b708d32015-12-11 19:07:01 -0800299 if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
Scott Anderson13081c62012-04-06 12:39:30 -0700300 }
Elliott Hughes1b708d32015-12-11 19:07:01 -0800301 putchar('\n');
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800302 }
303
304 return -1;
305}
306
David Pursell2ec418a2016-01-20 08:32:08 -0800307// Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
308// a specific device, otherwise the first USB device found will be used.
309//
Elliott Hughes855cdf82018-04-02 14:24:03 -0700310// If |serial| is non-null but invalid, this exits.
David Pursell2ec418a2016-01-20 08:32:08 -0800311// Otherwise it blocks until the target is available.
312//
313// The returned Transport is a singleton, so multiple calls to this function will return the same
314// object, and the caller should not attempt to delete the returned Transport.
David Pursell0b156632015-10-30 11:22:01 -0700315static Transport* open_device() {
David Pursell2ec418a2016-01-20 08:32:08 -0800316 bool announce = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317
David Pursell4601c972016-02-05 15:35:09 -0800318 Socket::Protocol protocol = Socket::Protocol::kTcp;
David Pursell2ec418a2016-01-20 08:32:08 -0800319 std::string host;
David Pursell4601c972016-02-05 15:35:09 -0800320 int port = 0;
321 if (serial != nullptr) {
322 const char* net_address = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800323
David Pursell4601c972016-02-05 15:35:09 -0800324 if (android::base::StartsWith(serial, "tcp:")) {
325 protocol = Socket::Protocol::kTcp;
326 port = tcp::kDefaultPort;
327 net_address = serial + strlen("tcp:");
328 } else if (android::base::StartsWith(serial, "udp:")) {
329 protocol = Socket::Protocol::kUdp;
330 port = udp::kDefaultPort;
331 net_address = serial + strlen("udp:");
332 }
333
334 if (net_address != nullptr) {
335 std::string error;
336 if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700337 die("invalid network address '%s': %s\n", net_address, error.c_str());
David Pursell4601c972016-02-05 15:35:09 -0800338 }
David Pursell2ec418a2016-01-20 08:32:08 -0800339 }
340 }
341
David Anderson1d887432018-08-27 16:47:32 -0700342 Transport* transport = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800343 while (true) {
344 if (!host.empty()) {
345 std::string error;
David Pursell4601c972016-02-05 15:35:09 -0800346 if (protocol == Socket::Protocol::kTcp) {
347 transport = tcp::Connect(host, port, &error).release();
348 } else if (protocol == Socket::Protocol::kUdp) {
349 transport = udp::Connect(host, port, &error).release();
350 }
351
David Pursell2ec418a2016-01-20 08:32:08 -0800352 if (transport == nullptr && announce) {
353 fprintf(stderr, "error: %s\n", error.c_str());
354 }
355 } else {
356 transport = usb_open(match_fastboot);
357 }
358
359 if (transport != nullptr) {
360 return transport;
361 }
362
David Pursell0b156632015-10-30 11:22:01 -0700363 if (announce) {
David Pursell2ec418a2016-01-20 08:32:08 -0800364 announce = false;
Elliott Hughesb46964f2015-08-19 17:49:45 -0700365 fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800366 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800367 std::this_thread::sleep_for(std::chrono::milliseconds(1));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800368 }
369}
370
Elliott Hughesfc797672015-04-07 20:12:50 -0700371static void list_devices() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800372 // We don't actually open a USB device here,
373 // just getting our callback called so we can
374 // list all the connected devices.
375 usb_open(list_devices_callback);
376}
377
Elliott Hughesd6365a72017-05-08 18:04:49 -0700378static void syntax_error(const char* fmt, ...) {
379 fprintf(stderr, "fastboot: usage: ");
380
381 va_list ap;
382 va_start(ap, fmt);
383 vfprintf(stderr, fmt, ap);
384 va_end(ap);
385
386 fprintf(stderr, "\n");
387 exit(1);
388}
389
390static int show_help() {
391 // clang-format off
392 fprintf(stdout,
Elliott Hughes07fc6822018-05-24 16:36:05 -0700393// 1 2 3 4 5 6 7 8
394// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
Elliott Hughesb76188f2018-04-03 13:30:18 -0700395 "usage: fastboot [OPTION...] COMMAND...\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800396 "\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700397 "flashing:\n"
398 " update ZIP Flash all partitions from an update.zip package.\n"
399 " flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
400 " On A/B devices, flashed slot is set as active.\n"
401 " Secondary images may be flashed to inactive slot.\n"
Elliott Hughes07fc6822018-05-24 16:36:05 -0700402 " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
403 " $ANDROID_PRODUCT_OUT if no filename is given.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700404 "\n"
405 "basics:\n"
406 " devices [-l] List devices in bootloader (-l: with device paths).\n"
407 " getvar NAME Display given bootloader variable.\n"
408 " reboot [bootloader] Reboot device.\n"
409 "\n"
410 "locking/unlocking:\n"
411 " flashing lock|unlock Lock/unlock partitions for flashing\n"
412 " flashing lock_critical|unlock_critical\n"
413 " Lock/unlock 'critical' bootloader partitions.\n"
414 " flashing get_unlock_ability\n"
415 " Check whether unlocking is allowed (1) or not(0).\n"
416 "\n"
417 "advanced:\n"
418 " erase PARTITION Erase a flash partition.\n"
419 " format[:FS_TYPE[:SIZE]] PARTITION\n"
420 " Format a flash partition.\n"
421 " set_active SLOT Set the active slot.\n"
422 " oem [COMMAND...] Execute OEM-specific command.\n"
David Anderson1d504e32019-01-15 14:38:20 -0800423 " gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
David Anderson7c84b9f2019-06-27 22:15:29 -0700424 " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
425 " contain an empty set of default dynamic partitions.\n"
Luca Stefani173667b2021-04-12 19:16:43 +0200426 " create-logical-partition NAME SIZE\n"
427 " Create a logical partition with the given name and\n"
428 " size, in the super partition.\n"
429 " delete-logical-partition NAME\n"
430 " Delete a logical partition with the given name.\n"
431 " resize-logical-partition NAME SIZE\n"
432 " Change the size of the named logical partition.\n"
David Andersonab8f4662019-10-21 16:45:59 -0700433 " snapshot-update cancel On devices that support snapshot-based updates, cancel\n"
434 " an in-progress update. This may make the device\n"
435 " unbootable until it is reflashed.\n"
David Anderson220ddb12019-10-31 18:02:41 -0700436 " snapshot-update merge On devices that support snapshot-based updates, finish\n"
437 " an in-progress update if it is in the \"merging\"\n"
438 " phase.\n"
Pierre-ClƩment Tosi96941a02021-06-14 12:16:06 +0000439 " fetch PARTITION OUT_FILE Fetch a partition image from the device."
Elliott Hughesb76188f2018-04-03 13:30:18 -0700440 "\n"
441 "boot image:\n"
442 " boot KERNEL [RAMDISK [SECOND]]\n"
443 " Download and boot kernel from RAM.\n"
444 " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
445 " Create boot image and flash it.\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800446 " --dtb DTB Specify path to DTB for boot image header version 2.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700447 " --cmdline CMDLINE Override kernel command line.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700448 " --base ADDRESS Set kernel base address (default: 0x10000000).\n"
449 " --kernel-offset Set kernel offset (default: 0x00008000).\n"
450 " --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
451 " --tags-offset Set tags offset (default: 0x00000100).\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800452 " --dtb-offset Set dtb offset (default: 0x01100000).\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700453 " --page-size BYTES Set flash page size (default: 2048).\n"
454 " --header-version VERSION Set boot image header version.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700455 " --os-version MAJOR[.MINOR[.PATCH]]\n"
456 " Set boot image OS version (default: 0.0.0).\n"
457 " --os-patch-level YYYY-MM-DD\n"
458 " Set boot image OS security patch level.\n"
459 // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
Elliott Hughesb76188f2018-04-03 13:30:18 -0700460 "\n"
Elliott Hughes2e9b7792018-04-04 13:36:44 -0700461 // TODO: what device(s) used this? is there any documentation?
Elliott Hughesb76188f2018-04-03 13:30:18 -0700462 //" continue Continue with autoboot.\n"
463 //"\n"
464 "Android Things:\n"
465 " stage IN_FILE Sends given file to stage for the next command.\n"
466 " 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 -0800467 "\n"
468 "options:\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700469 " -w Wipe userdata.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700470 " -s SERIAL Specify a USB device.\n"
471 " -s tcp|udp:HOST[:PORT] Specify a network device.\n"
Elliott Hughes542370d2018-04-19 19:49:44 -0700472 " -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
David Anderson89569642018-11-16 15:53:35 -0800473 " --force Force a flash operation that may be unsafe.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700474 " --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
475 " non-current slot (default: current active slot).\n"
476 " --set-active[=SLOT] Sets the active slot before rebooting.\n"
477 " --skip-secondary Don't flash secondary slots in flashall/update.\n"
478 " --skip-reboot Don't reboot device after flashing.\n"
479 " --disable-verity Sets disable-verity when flashing vbmeta.\n"
480 " --disable-verification Sets disable-verification when flashing vbmeta.\n"
Jaegeuk Kim638d05e2020-11-09 08:54:13 -0800481 " --fs-options=OPTION[,OPTION]\n"
482 " Enable filesystem features. OPTION supports casefold, projid, compress\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700483 // TODO: remove --unbuffered?
484 " --unbuffered Don't buffer input or output.\n"
485 " --verbose, -v Verbose output.\n"
486 " --version Display version.\n"
487 " --help, -h Show this message.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800488 );
Yifan Hongbcd27702021-02-16 19:37:32 -0800489 // clang-format on
Elliott Hughesd6365a72017-05-08 18:04:49 -0700490 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491}
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000492
Tom Cherrydfd85df2018-09-20 14:45:05 -0700493static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
494 const std::string& second_stage) {
495 std::vector<char> kernel_data;
496 if (!ReadFileToVector(kernel, &kernel_data)) {
497 die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
498 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800499
Elliott Hughesfc797672015-04-07 20:12:50 -0700500 // Is this actually a boot image?
Steve Muckle15303f22020-03-18 14:55:06 -0700501 if (kernel_data.size() < sizeof(boot_img_hdr_v3)) {
Elliott Hughesaaa3b6b2018-01-18 16:08:24 -0800502 die("cannot load '%s': too short", kernel.c_str());
503 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700504 if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
Elliott Hughes577e8b42018-04-05 16:12:47 -0700505 if (!g_cmdline.empty()) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800506 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
Elliott Hughes577e8b42018-04-05 16:12:47 -0700507 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800508
Elliott Hughes4089d342017-10-27 14:21:12 -0700509 if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800510
Tom Cherrydfd85df2018-09-20 14:45:05 -0700511 return kernel_data;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800512 }
513
Tom Cherrydfd85df2018-09-20 14:45:05 -0700514 std::vector<char> ramdisk_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700515 if (!ramdisk.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700516 if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
517 die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
518 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800519 }
520
Tom Cherrydfd85df2018-09-20 14:45:05 -0700521 std::vector<char> second_stage_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700522 if (!second_stage.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700523 if (!ReadFileToVector(second_stage, &second_stage_data)) {
524 die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
525 }
Jeremy Compostellaa42adff2014-07-17 17:17:54 +0200526 }
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800527
528 std::vector<char> dtb_data;
529 if (!g_dtb_path.empty()) {
Steve Muckle15303f22020-03-18 14:55:06 -0700530 if (g_boot_img_hdr.header_version != 2) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000531 die("Argument dtb not supported for boot image header version %d\n",
532 g_boot_img_hdr.header_version);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800533 }
534 if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
535 die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
536 }
537 }
538
Daniel Zheng65452d02022-11-30 02:25:31 +0000539 fprintf(stderr, "creating boot image...\n");
Elliott Hughesd6365a72017-05-08 18:04:49 -0700540
Tom Cherrydfd85df2018-09-20 14:45:05 -0700541 std::vector<char> out;
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800542 mkbootimg(kernel_data, ramdisk_data, second_stage_data, dtb_data, g_base_addr, g_boot_img_hdr,
543 &out);
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800544
Yi-Yo Chiangac4a1362021-03-25 01:14:52 +0800545 if (!g_cmdline.empty()) {
546 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(out.data()), g_cmdline);
547 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700548 fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700549 return out;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550}
551
Tom Cherrydfd85df2018-09-20 14:45:05 -0700552static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
553 std::vector<char>* out) {
Elliott Hughesb4074142020-09-15 14:26:17 -0700554 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700555 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700556 fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
557 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 }
559
Elliott Hughesb4074142020-09-15 14:26:17 -0700560 if (zip_entry.uncompressed_length > std::numeric_limits<size_t>::max()) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000561 die("entry '%s' is too large: %" PRIu64, entry_name.c_str(), zip_entry.uncompressed_length);
Elliott Hughesb4074142020-09-15 14:26:17 -0700562 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700563 out->resize(zip_entry.uncompressed_length);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564
Tom Cherrydfd85df2018-09-20 14:45:05 -0700565 fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
566 out->size() / 1024 / 1024);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567
Daniel Zheng65452d02022-11-30 02:25:31 +0000568 int error =
569 ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()), out->size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700570 if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000571
Tom Cherrydfd85df2018-09-20 14:45:05 -0700572 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573}
574
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700575#if defined(_WIN32)
576
577// TODO: move this to somewhere it can be shared.
578
579#include <windows.h>
580
581// Windows' tmpfile(3) requires administrator rights because
582// it creates temporary files in the root directory.
583static FILE* win32_tmpfile() {
584 char temp_path[PATH_MAX];
585 DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
586 if (nchars == 0 || nchars >= sizeof(temp_path)) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700587 die("GetTempPath failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700588 }
589
590 char filename[PATH_MAX];
591 if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700592 die("GetTempFileName failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700593 }
594
595 return fopen(filename, "w+bTD");
596}
597
598#define tmpfile win32_tmpfile
599
Elliott Hughes855cdf82018-04-02 14:24:03 -0700600static int make_temporary_fd(const char* /*what*/) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700601 // TODO: reimplement to avoid leaking a FILE*.
602 return fileno(tmpfile());
603}
604
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000605#else
606
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700607static std::string make_temporary_template() {
608 const char* tmpdir = getenv("TMPDIR");
609 if (tmpdir == nullptr) tmpdir = P_tmpdir;
610 return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
611}
612
Elliott Hughes855cdf82018-04-02 14:24:03 -0700613static int make_temporary_fd(const char* what) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700614 std::string path_template(make_temporary_template());
615 int fd = mkstemp(&path_template[0]);
616 if (fd == -1) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000617 die("failed to create temporary file for %s with template %s: %s\n", path_template.c_str(),
618 what, strerror(errno));
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700619 }
620 unlink(path_template.c_str());
621 return fd;
622}
623
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700624#endif
625
Yifan Hongb10d0672021-02-22 15:06:27 -0800626static unique_fd unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700627 unique_fd fd(make_temporary_fd(entry_name));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700628
Elliott Hughesb4074142020-09-15 14:26:17 -0700629 ZipEntry64 zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700630 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700631 fprintf(stderr, "archive does not contain '%s'\n", entry_name);
David Andersoncf444f32018-08-29 14:15:49 -0700632 errno = ENOENT;
Yifan Hongb10d0672021-02-22 15:06:27 -0800633 return unique_fd();
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000634 }
635
Elliott Hughesb4074142020-09-15 14:26:17 -0700636 fprintf(stderr, "extracting %s (%" PRIu64 " MB) to disk...", entry_name,
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700637 zip_entry.uncompressed_length / 1024 / 1024);
Elliott Hughes23af1122017-11-10 08:42:17 -0800638 double start = now();
Yifan Hong58532df2021-03-22 16:39:13 -0700639 int error = ExtractEntryToFile(zip, &zip_entry, fd.get());
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700640 if (error != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800641 die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700642 }
643
Yifan Hong58532df2021-03-22 16:39:13 -0700644 if (lseek(fd.get(), 0, SEEK_SET) != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800645 die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
Elliott Hughes4089d342017-10-27 14:21:12 -0700646 }
647
Elliott Hughes23af1122017-11-10 08:42:17 -0800648 fprintf(stderr, " took %.3fs\n", now() - start);
649
Yifan Hongb10d0672021-02-22 15:06:27 -0800650 return fd;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700651}
652
Andrew Chantd64b9882021-04-06 12:48:27 -0700653static bool CheckRequirement(const std::string& cur_product, const std::string& var,
Tom Cherry4aa60b32018-09-05 15:11:44 -0700654 const std::string& product, bool invert,
655 const std::vector<std::string>& options) {
656 Status("Checking '" + var + "'");
Elliott Hughes5620d222018-03-28 08:20:00 -0700657
Tom Cherry4aa60b32018-09-05 15:11:44 -0700658 double start = now();
659
660 if (!product.empty()) {
661 if (product != cur_product) {
662 double split = now();
663 fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
664 cur_product.c_str(), product.c_str(), (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700665 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700666 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800667 }
Tom Cherry4aa60b32018-09-05 15:11:44 -0700668
669 std::string var_value;
Tom Cherry9027af02018-09-24 15:48:09 -0700670 if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700671 fprintf(stderr, "FAILED\n\n");
Daniel Zheng65452d02022-11-30 02:25:31 +0000672 fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(), fb->Error().c_str());
Andrew Chantd64b9882021-04-06 12:48:27 -0700673 return false;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700674 }
675
676 bool match = false;
677 for (const auto& option : options) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000678 if (option == var_value ||
679 (option.back() == '*' &&
680 !var_value.compare(0, option.length() - 1, option, 0, option.length() - 1))) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700681 match = true;
682 break;
683 }
684 }
685
686 if (invert) {
687 match = !match;
688 }
689
690 if (match) {
691 double split = now();
692 fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
Andrew Chantd64b9882021-04-06 12:48:27 -0700693 return true;
Tom Cherry4aa60b32018-09-05 15:11:44 -0700694 }
695
696 fprintf(stderr, "FAILED\n\n");
697 fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
698 fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
699 for (auto it = std::next(options.begin()); it != options.end(); ++it) {
700 fprintf(stderr, " or '%s'", it->c_str());
701 }
702 fprintf(stderr, ".\n\n");
Andrew Chantd64b9882021-04-06 12:48:27 -0700703 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800704}
705
Tom Cherry4aa60b32018-09-05 15:11:44 -0700706bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
707 bool* invert, std::vector<std::string>* options) {
Elliott Hughes5620d222018-03-28 08:20:00 -0700708 // "require product=alpha|beta|gamma"
709 // "require version-bootloader=1234"
710 // "require-for-product:gamma version-bootloader=istanbul|constantinople"
711 // "require partition-exists=vendor"
Tom Cherry4aa60b32018-09-05 15:11:44 -0700712 *product = "";
713 *invert = false;
Elliott Hughes5620d222018-03-28 08:20:00 -0700714
Tom Cherry4aa60b32018-09-05 15:11:44 -0700715 auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
716 auto require_product_regex =
717 std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
718 std::smatch match_results;
719
720 if (std::regex_match(line, match_results, require_reject_regex)) {
721 *invert = Trim(match_results[1]) == "reject";
722 } else if (std::regex_match(line, match_results, require_product_regex)) {
723 *product = match_results[1];
724 } else {
725 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726 }
727
Tom Cherry4aa60b32018-09-05 15:11:44 -0700728 *name = match_results[2];
Elliott Hughes253c18d2015-03-18 22:47:09 -0700729 // Work around an unfortunate name mismatch.
Tom Cherry4aa60b32018-09-05 15:11:44 -0700730 if (*name == "board") {
731 *name = "product";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800732 }
733
Tom Cherry4aa60b32018-09-05 15:11:44 -0700734 auto raw_options = Split(match_results[3], "|");
735 for (const auto& option : raw_options) {
736 auto trimmed_option = Trim(option);
737 options->emplace_back(trimmed_option);
738 }
739
740 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741}
742
Tom Cherry4aa60b32018-09-05 15:11:44 -0700743// "require partition-exists=x" is a special case, added because of the trouble we had when
744// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
745// missing out new partitions. A device with new partitions can use "partition-exists" to
746// override the fields `optional_if_no_image` in the `images` array.
747static void HandlePartitionExists(const std::vector<std::string>& options) {
748 const std::string& partition_name = options[0];
749 std::string has_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700750 if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
Tom Cherry4aa60b32018-09-05 15:11:44 -0700751 (has_slot != "yes" && has_slot != "no")) {
752 die("device doesn't have required partition %s!", partition_name.c_str());
753 }
754 bool known_partition = false;
Daniel Zheng65452d02022-11-30 02:25:31 +0000755 for (size_t i = 0; i < images.size(); ++i) {
756 if (!images[i].nickname.empty() && images[i].nickname == partition_name) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700757 images[i].optional_if_no_image = false;
758 known_partition = true;
759 }
760 }
761 if (!known_partition) {
762 die("device requires partition %s which is not known to this version of fastboot",
763 partition_name.c_str());
764 }
765}
766
Andrew Chantd64b9882021-04-06 12:48:27 -0700767static void CheckRequirements(const std::string& data, bool force_flash) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700768 std::string cur_product;
Tom Cherry9027af02018-09-24 15:48:09 -0700769 if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
770 fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700771 }
772
773 auto lines = Split(data, "\n");
774 for (const auto& line : lines) {
775 if (line.empty()) {
776 continue;
777 }
778
779 std::string name;
780 std::string product;
781 bool invert;
782 std::vector<std::string> options;
783
784 if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
785 fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
786 continue;
787 }
788 if (name == "partition-exists") {
789 HandlePartitionExists(options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800790 } else {
Andrew Chantd64b9882021-04-06 12:48:27 -0700791 bool met = CheckRequirement(cur_product, name, product, invert, options);
792 if (!met) {
793 if (!force_flash) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000794 die("requirements not met!");
Andrew Chantd64b9882021-04-06 12:48:27 -0700795 } else {
Daniel Zheng65452d02022-11-30 02:25:31 +0000796 fprintf(stderr, "requirements not met! but proceeding due to --force\n");
Andrew Chantd64b9882021-04-06 12:48:27 -0700797 }
798 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800799 }
800 }
801}
802
Tom Cherry9027af02018-09-24 15:48:09 -0700803static void DisplayVarOrError(const std::string& label, const std::string& var) {
804 std::string value;
805
806 if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
807 Status("getvar:" + var);
808 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
809 return;
810 }
811 fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
812}
813
814static void DumpInfo() {
815 fprintf(stderr, "--------------------------------------------\n");
816 DisplayVarOrError("Bootloader Version...", "version-bootloader");
817 DisplayVarOrError("Baseband Version.....", "version-baseband");
818 DisplayVarOrError("Serial Number........", "serialno");
819 fprintf(stderr, "--------------------------------------------\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820}
821
David Andersonaa87dc52023-01-27 20:39:06 -0800822static std::vector<SparsePtr> resparse_file(sparse_file* s, int64_t max_size) {
Tao Bao41cf35f2018-04-24 10:54:21 -0700823 if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
Daniel Zheng65452d02022-11-30 02:25:31 +0000824 die("invalid max size %" PRId64, max_size);
Tao Bao41cf35f2018-04-24 10:54:21 -0700825 }
826
David Andersonaa87dc52023-01-27 20:39:06 -0800827 const int files = sparse_file_resparse(s, max_size, nullptr, 0);
Elliott Hughes4089d342017-10-27 14:21:12 -0700828 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700829
David Andersona1c983e2023-01-27 11:57:27 -0800830 auto temp = std::make_unique<sparse_file*[]>(files);
David Andersonaa87dc52023-01-27 20:39:06 -0800831 const int rv = sparse_file_resparse(s, max_size, temp.get(), files);
David Andersona1c983e2023-01-27 11:57:27 -0800832 if (rv < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700833
David Andersona1c983e2023-01-27 11:57:27 -0800834 std::vector<SparsePtr> out_s;
835 for (int i = 0; i < files; i++) {
836 out_s.emplace_back(temp[i], sparse_file_destroy);
837 }
Colin Crossf8387882012-05-24 17:18:41 -0700838 return out_s;
839}
840
David Andersonaa87dc52023-01-27 20:39:06 -0800841static std::vector<SparsePtr> load_sparse_files(int fd, int64_t max_size) {
842 SparsePtr s(sparse_file_import_auto(fd, false, true), sparse_file_destroy);
843 if (!s) die("cannot sparse read file");
844
845 return resparse_file(s.get(), max_size);
846}
847
Yifan Hongbcd27702021-02-16 19:37:32 -0800848static uint64_t get_uint_var(const char* var_name) {
849 std::string value_str;
850 if (fb->GetVar(var_name, &value_str) != fastboot::SUCCESS || value_str.empty()) {
851 verbose("target didn't report %s", var_name);
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700852 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700853 }
854
Elliott Hughes77c0e662015-11-02 15:51:12 -0800855 // Some bootloaders (angler, for example) send spurious whitespace too.
Yifan Hongbcd27702021-02-16 19:37:32 -0800856 value_str = android::base::Trim(value_str);
Elliott Hughes77c0e662015-11-02 15:51:12 -0800857
Yifan Hongbcd27702021-02-16 19:37:32 -0800858 uint64_t value;
859 if (!android::base::ParseUint(value_str, &value)) {
860 fprintf(stderr, "couldn't parse %s '%s'\n", var_name, value_str.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700861 return 0;
862 }
Yifan Hongbcd27702021-02-16 19:37:32 -0800863 if (value > 0) verbose("target reported %s of %" PRId64 " bytes", var_name, value);
864 return value;
Colin Crossf8387882012-05-24 17:18:41 -0700865}
866
Aaron Wisnerdb511202018-06-26 15:38:35 -0500867static int64_t get_sparse_limit(int64_t size) {
Elliott Hughes542370d2018-04-19 19:49:44 -0700868 int64_t limit = sparse_limit;
869 if (limit == 0) {
870 // Unlimited, so see what the target device's limit is.
871 // TODO: shouldn't we apply this limit even if you've used -S?
Colin Crossf8387882012-05-24 17:18:41 -0700872 if (target_sparse_limit == -1) {
Yifan Hongbcd27702021-02-16 19:37:32 -0800873 target_sparse_limit = static_cast<int64_t>(get_uint_var("max-download-size"));
Colin Crossf8387882012-05-24 17:18:41 -0700874 }
875 if (target_sparse_limit > 0) {
876 limit = target_sparse_limit;
877 } else {
Colin Cross0bbfb392012-07-24 18:05:21 -0700878 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700879 }
880 }
881
882 if (size > limit) {
Chris Fries6a999712017-04-04 09:52:47 -0500883 return std::min(limit, RESPARSE_LIMIT);
Colin Crossf8387882012-05-24 17:18:41 -0700884 }
885
886 return 0;
887}
888
Yifan Hongb10d0672021-02-22 15:06:27 -0800889static bool load_buf_fd(unique_fd fd, struct fastboot_buffer* buf) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700890 int64_t sz = get_file_size(fd);
891 if (sz == -1) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700892 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700893 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -0700894
Yifan Hong58532df2021-03-22 16:39:13 -0700895 if (sparse_file* s = sparse_file_import(fd.get(), false, false)) {
David Anderson32e376f2018-08-16 13:43:11 -0700896 buf->image_size = sparse_file_len(s, false, false);
897 sparse_file_destroy(s);
898 } else {
899 buf->image_size = sz;
900 }
901
Yifan Hong58532df2021-03-22 16:39:13 -0700902 lseek(fd.get(), 0, SEEK_SET);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500903 int64_t limit = get_sparse_limit(sz);
Yifan Honge9f067b2021-03-22 16:55:39 -0700904 buf->fd = std::move(fd);
Colin Crossf8387882012-05-24 17:18:41 -0700905 if (limit) {
David Andersona1c983e2023-01-27 11:57:27 -0800906 buf->files = load_sparse_files(buf->fd.get(), limit);
907 if (buf->files.empty()) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700908 return false;
Colin Crossf8387882012-05-24 17:18:41 -0700909 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700910 buf->type = FB_BUFFER_SPARSE;
Colin Crossf8387882012-05-24 17:18:41 -0700911 } else {
Chris Fries0ea946c2017-04-12 10:25:57 -0500912 buf->type = FB_BUFFER_FD;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000913 buf->sz = sz;
Colin Crossf8387882012-05-24 17:18:41 -0700914 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700915
Elliott Hughes53ec4952016-05-11 12:39:27 -0700916 return true;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700917}
918
Aaron Wisnerdb511202018-06-26 15:38:35 -0500919static bool load_buf(const char* fname, struct fastboot_buffer* buf) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500920 unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
921
Elliott Hughes53ec4952016-05-11 12:39:27 -0700922 if (fd == -1) {
923 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700924 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500925
926 struct stat s;
Yifan Hong58532df2021-03-22 16:39:13 -0700927 if (fstat(fd.get(), &s)) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500928 return false;
929 }
930 if (!S_ISREG(s.st_mode)) {
931 errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
932 return false;
933 }
934
Yifan Hongb10d0672021-02-22 15:06:27 -0800935 return load_buf_fd(std::move(fd), buf);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700936}
937
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800938static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf, bool vbmeta_in_boot) {
David Zeuthenb6ea4352017-08-07 14:29:26 -0400939 // Buffer needs to be at least the size of the VBMeta struct which
940 // is 256 bytes.
941 if (buf->sz < 256) {
942 return;
943 }
944
David Zeuthenb6ea4352017-08-07 14:29:26 -0400945 std::string data;
946 if (!android::base::ReadFdToString(buf->fd, &data)) {
947 die("Failed reading from vbmeta");
948 }
949
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800950 uint64_t vbmeta_offset = 0;
951 if (vbmeta_in_boot) {
952 // Tries to locate top-level vbmeta from boot.img footer.
953 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
954 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
Bowgo Tsai671249a2021-08-10 16:32:37 +0800955 die("Failed to find AVB_FOOTER at offset: %" PRId64 ", is BOARD_AVB_ENABLE true?",
956 footer_offset);
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800957 }
958 const AvbFooter* footer = reinterpret_cast<const AvbFooter*>(data.c_str() + footer_offset);
959 vbmeta_offset = be64toh(footer->vbmeta_offset);
960 }
961 // Ensures there is AVB_MAGIC at vbmeta_offset.
962 if (0 != data.compare(vbmeta_offset, AVB_MAGIC_LEN, AVB_MAGIC)) {
963 die("Failed to find AVB_MAGIC at offset: %" PRId64, vbmeta_offset);
964 }
965
966 fprintf(stderr, "Rewriting vbmeta struct at offset: %" PRId64 "\n", vbmeta_offset);
967
David Zeuthenb6ea4352017-08-07 14:29:26 -0400968 // There's a 32-bit big endian |flags| field at offset 120 where
969 // bit 0 corresponds to disable-verity and bit 1 corresponds to
970 // disable-verification.
971 //
972 // See external/avb/libavb/avb_vbmeta_image.h for the layout of
973 // the VBMeta struct.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800974 uint64_t flags_offset = 123 + vbmeta_offset;
David Zeuthenb6ea4352017-08-07 14:29:26 -0400975 if (g_disable_verity) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800976 data[flags_offset] |= 0x01;
David Zeuthenb6ea4352017-08-07 14:29:26 -0400977 }
978 if (g_disable_verification) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800979 data[flags_offset] |= 0x02;
David Zeuthenb6ea4352017-08-07 14:29:26 -0400980 }
981
Yifan Hongb10d0672021-02-22 15:06:27 -0800982 unique_fd fd(make_temporary_fd("vbmeta rewriting"));
David Zeuthenb6ea4352017-08-07 14:29:26 -0400983 if (!android::base::WriteStringToFd(data, fd)) {
984 die("Failed writing to modified vbmeta");
985 }
Yifan Hongb10d0672021-02-22 15:06:27 -0800986 buf->fd = std::move(fd);
Yifan Hong58532df2021-03-22 16:39:13 -0700987 lseek(buf->fd.get(), 0, SEEK_SET);
David Zeuthenb6ea4352017-08-07 14:29:26 -0400988}
989
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +0800990static bool has_vbmeta_partition() {
991 std::string partition_type;
992 return fb->GetVar("partition-type:vbmeta", &partition_type) == fastboot::SUCCESS ||
993 fb->GetVar("partition-type:vbmeta_a", &partition_type) == fastboot::SUCCESS ||
994 fb->GetVar("partition-type:vbmeta_b", &partition_type) == fastboot::SUCCESS;
995}
996
David Andersonaa87dc52023-01-27 20:39:06 -0800997// Note: this only works in userspace fastboot. In the bootloader, use
998// should_flash_in_userspace().
Michael Bestasa495be72020-11-06 17:58:28 +0200999static bool is_logical(const std::string& partition) {
1000 std::string value;
1001 return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1002}
1003
Steve Muckle3af575b2020-06-18 17:02:15 -07001004static std::string fb_fix_numeric_var(std::string var) {
1005 // Some bootloaders (angler, for example), send spurious leading whitespace.
1006 var = android::base::Trim(var);
1007 // Some bootloaders (hammerhead, for example) use implicit hex.
1008 // This code used to use strtol with base 16.
1009 if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
1010 return var;
1011}
1012
Yifan Hongbcd27702021-02-16 19:37:32 -08001013static uint64_t get_partition_size(const std::string& partition) {
Steve Muckle3af575b2020-06-18 17:02:15 -07001014 std::string partition_size_str;
1015 if (fb->GetVar("partition-size:" + partition, &partition_size_str) != fastboot::SUCCESS) {
Michael Bestasa495be72020-11-06 17:58:28 +02001016 if (!is_logical(partition)) {
1017 return 0;
1018 }
Yifan Hong60de9692021-02-17 13:51:54 -08001019 die("cannot get partition size for %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001020 }
1021
1022 partition_size_str = fb_fix_numeric_var(partition_size_str);
Yifan Hongbcd27702021-02-16 19:37:32 -08001023 uint64_t partition_size;
1024 if (!android::base::ParseUint(partition_size_str, &partition_size)) {
Michael Bestasa495be72020-11-06 17:58:28 +02001025 if (!is_logical(partition)) {
1026 return 0;
1027 }
Steve Muckle3af575b2020-06-18 17:02:15 -07001028 die("Couldn't parse partition size '%s'.", partition_size_str.c_str());
1029 }
Yifan Hongbcd27702021-02-16 19:37:32 -08001030 return partition_size;
1031}
1032
Devin Moorecb5098f2022-01-07 16:33:46 +00001033static void copy_avb_footer(const std::string& partition, struct fastboot_buffer* buf) {
Yifan Hongbcd27702021-02-16 19:37:32 -08001034 if (buf->sz < AVB_FOOTER_SIZE) {
1035 return;
1036 }
1037
Bowgo Tsai671249a2021-08-10 16:32:37 +08001038 // If overflows and negative, it should be < buf->sz.
1039 int64_t partition_size = static_cast<int64_t>(get_partition_size(partition));
1040
1041 if (partition_size == buf->sz) {
1042 return;
1043 }
1044 // Some device bootloaders might not implement `fastboot getvar partition-size:boot[_a|_b]`.
1045 // In this case, partition_size will be zero.
1046 if (partition_size < buf->sz) {
1047 fprintf(stderr,
Devin Moorecb5098f2022-01-07 16:33:46 +00001048 "Warning: skip copying %s image avb footer"
1049 " (%s partition size: %" PRId64 ", %s image size: %" PRId64 ").\n",
1050 partition.c_str(), partition.c_str(), partition_size, partition.c_str(), buf->sz);
Bowgo Tsai671249a2021-08-10 16:32:37 +08001051 return;
1052 }
1053
1054 // IMPORTANT: after the following read, we need to reset buf->fd before return (if not die).
1055 // Because buf->fd will still be used afterwards.
Steve Muckle3af575b2020-06-18 17:02:15 -07001056 std::string data;
1057 if (!android::base::ReadFdToString(buf->fd, &data)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001058 die("Failed reading from %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001059 }
1060
1061 uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
1062 if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
Bowgo Tsai671249a2021-08-10 16:32:37 +08001063 lseek(buf->fd.get(), 0, SEEK_SET); // IMPORTANT: resets buf->fd before return.
Steve Muckle3af575b2020-06-18 17:02:15 -07001064 return;
1065 }
1066
Devin Moorecb5098f2022-01-07 16:33:46 +00001067 const std::string tmp_fd_template = partition + " rewriting";
1068 unique_fd fd(make_temporary_fd(tmp_fd_template.c_str()));
Steve Muckle3af575b2020-06-18 17:02:15 -07001069 if (!android::base::WriteStringToFd(data, fd)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001070 die("Failed writing to modified %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001071 }
Yifan Hong58532df2021-03-22 16:39:13 -07001072 lseek(fd.get(), partition_size - AVB_FOOTER_SIZE, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001073 if (!android::base::WriteStringToFd(data.substr(footer_offset), fd)) {
Devin Moorecb5098f2022-01-07 16:33:46 +00001074 die("Failed copying AVB footer in %s", partition.c_str());
Steve Muckle3af575b2020-06-18 17:02:15 -07001075 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001076 buf->fd = std::move(fd);
Steve Muckle3af575b2020-06-18 17:02:15 -07001077 buf->sz = partition_size;
Yifan Hong58532df2021-03-22 16:39:13 -07001078 lseek(buf->fd.get(), 0, SEEK_SET);
Steve Muckle3af575b2020-06-18 17:02:15 -07001079}
1080
David Andersonaa87dc52023-01-27 20:39:06 -08001081static void flash_partition_files(const std::string& partition,
1082 const std::vector<SparsePtr>& files) {
1083 for (size_t i = 0; i < files.size(); i++) {
1084 sparse_file* s = files[i].get();
1085 int64_t sz = sparse_file_len(s, true, false);
1086 fb->FlashPartition(partition, s, sz, i + 1, files.size());
1087 }
1088}
1089
Daniel Zheng65452d02022-11-30 02:25:31 +00001090static void flash_buf(const std::string& partition, struct fastboot_buffer* buf) {
Devin Moore1af12022022-01-06 01:11:23 +00001091 if (partition == "boot" || partition == "boot_a" || partition == "boot_b" ||
Isaac J. Manjarresacb49522023-01-12 14:28:29 -08001092 partition == "init_boot" || partition == "init_boot_a" || partition == "init_boot_b" ||
1093 partition == "recovery" || partition == "recovery_a" || partition == "recovery_b") {
Devin Moorecb5098f2022-01-07 16:33:46 +00001094 copy_avb_footer(partition, buf);
Steve Muckle3af575b2020-06-18 17:02:15 -07001095 }
1096
David Zeuthenb6ea4352017-08-07 14:29:26 -04001097 // Rewrite vbmeta if that's what we're flashing and modification has been requested.
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001098 if (g_disable_verity || g_disable_verification) {
Paweł Grabasff9cfac2021-03-04 13:11:25 +01001099 // The vbmeta partition might have additional prefix if running in virtual machine
1100 // e.g., guest_vbmeta_a.
1101 if (android::base::EndsWith(partition, "vbmeta") ||
1102 android::base::EndsWith(partition, "vbmeta_a") ||
1103 android::base::EndsWith(partition, "vbmeta_b")) {
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001104 rewrite_vbmeta_buffer(buf, false /* vbmeta_in_boot */);
1105 } else if (!has_vbmeta_partition() &&
1106 (partition == "boot" || partition == "boot_a" || partition == "boot_b")) {
Daniel Zheng65452d02022-11-30 02:25:31 +00001107 rewrite_vbmeta_buffer(buf, true /* vbmeta_in_boot */);
Chin-Ting Kuodf6a7802019-09-16 11:23:55 +08001108 }
David Zeuthenb6ea4352017-08-07 14:29:26 -04001109 }
1110
Rom Lemarchand622810c2013-06-28 09:54:59 -07001111 switch (buf->type) {
Josh Gao9da9ac52016-01-19 14:50:18 -08001112 case FB_BUFFER_SPARSE: {
David Andersonaa87dc52023-01-27 20:39:06 -08001113 flash_partition_files(partition, buf->files);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001114 break;
Josh Gao9da9ac52016-01-19 14:50:18 -08001115 }
Chris Fries0ea946c2017-04-12 10:25:57 -05001116 case FB_BUFFER_FD:
Tom Cherry9027af02018-09-24 15:48:09 -07001117 fb->FlashPartition(partition, buf->fd, buf->sz);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001118 break;
1119 default:
1120 die("unknown buffer type: %d", buf->type);
1121 }
1122}
1123
Aaron Wisnerdb511202018-06-26 15:38:35 -05001124static std::string get_current_slot() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001125 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07001126 if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
LuK1337dae48ef2020-04-06 14:38:58 +02001127 if (current_slot[0] == '_') current_slot.erase(0, 1);
Elliott Hughes42b18a52018-04-10 15:32:21 -07001128 return current_slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001129}
1130
Aaron Wisnerdb511202018-06-26 15:38:35 -05001131static int get_slot_count() {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001132 std::string var;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001133 int count = 0;
Tom Cherry9027af02018-09-24 15:48:09 -07001134 if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
1135 !android::base::ParseInt(var, &count)) {
Elliott Hughes42b18a52018-04-10 15:32:21 -07001136 return 0;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001137 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001138 return count;
1139}
1140
Aaron Wisnerdb511202018-06-26 15:38:35 -05001141static bool supports_AB() {
Daniel Zheng65452d02022-11-30 02:25:31 +00001142 return get_slot_count() >= 2;
Alex Lightbb9b8a52016-06-29 09:26:44 -07001143}
1144
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001145// Given a current slot, this returns what the 'other' slot is.
Daniel Rosenberg80919472016-06-30 19:25:31 -07001146static std::string get_other_slot(const std::string& current_slot, int count) {
1147 if (count == 0) return "";
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001148
Daniel Zheng65452d02022-11-30 02:25:31 +00001149 char next = (current_slot[0] - 'a' + 1) % count + 'a';
Daniel Rosenberg80919472016-06-30 19:25:31 -07001150 return std::string(1, next);
1151}
1152
Aaron Wisnerdb511202018-06-26 15:38:35 -05001153static std::string get_other_slot(const std::string& current_slot) {
1154 return get_other_slot(current_slot, get_slot_count());
Daniel Rosenberg80919472016-06-30 19:25:31 -07001155}
1156
Aaron Wisnerdb511202018-06-26 15:38:35 -05001157static std::string get_other_slot(int count) {
1158 return get_other_slot(get_current_slot(), count);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001159}
1160
Aaron Wisnerdb511202018-06-26 15:38:35 -05001161static std::string get_other_slot() {
1162 return get_other_slot(get_current_slot(), get_slot_count());
Alex Lightbb9b8a52016-06-29 09:26:44 -07001163}
1164
Aaron Wisnerdb511202018-06-26 15:38:35 -05001165static std::string verify_slot(const std::string& slot_name, bool allow_all) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001166 std::string slot = slot_name;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001167 if (slot == "all") {
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001168 if (allow_all) {
1169 return "all";
1170 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001171 int count = get_slot_count();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001172 if (count > 0) {
1173 return "a";
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001174 } else {
Elliott Hughes4089d342017-10-27 14:21:12 -07001175 die("No known slots");
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001176 }
1177 }
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001178 }
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001179
Aaron Wisnerdb511202018-06-26 15:38:35 -05001180 int count = get_slot_count();
Elliott Hughes4089d342017-10-27 14:21:12 -07001181 if (count == 0) die("Device does not support slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001182
Daniel Rosenberg80919472016-06-30 19:25:31 -07001183 if (slot == "other") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001184 std::string other = get_other_slot(count);
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001185 if (other == "") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001186 die("No known slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001187 }
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001188 return other;
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001189 }
1190
Daniel Zheng65452d02022-11-30 02:25:31 +00001191 if (slot.size() == 1 && (slot[0] - 'a' >= 0 && slot[0] - 'a' < count)) return slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001192
1193 fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
Daniel Zheng65452d02022-11-30 02:25:31 +00001194 for (int i = 0; i < count; i++) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001195 fprintf(stderr, "%c\n", (char)(i + 'a'));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001196 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001197
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001198 exit(1);
1199}
1200
Aaron Wisnerdb511202018-06-26 15:38:35 -05001201static std::string verify_slot(const std::string& slot) {
Daniel Zheng65452d02022-11-30 02:25:31 +00001202 return verify_slot(slot, true);
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001203}
1204
Aaron Wisnerdb511202018-06-26 15:38:35 -05001205static void do_for_partition(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001206 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001207 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001208 std::string current_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001209 // |part| can be vendor_boot:default. Append slot to the first token.
1210 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001211
Yifan Hong6d7da632021-02-23 12:15:51 -08001212 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001213 /* If has-slot is not supported, the answer is no. */
1214 has_slot = "no";
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001215 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001216 if (has_slot == "yes") {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001217 if (slot == "") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001218 current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001219 if (current_slot == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001220 die("Failed to identify current slot");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001221 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001222 part_tokens[0] += "_" + current_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001223 } else {
Yifan Hong6d7da632021-02-23 12:15:51 -08001224 part_tokens[0] += "_" + slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001225 }
Yifan Hong6d7da632021-02-23 12:15:51 -08001226 func(android::base::Join(part_tokens, ":"));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001227 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001228 if (force_slot && slot != "") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001229 fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
1230 part_tokens[0].c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001231 }
1232 func(part);
1233 }
1234}
1235
David Pursell0b156632015-10-30 11:22:01 -07001236/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1237 * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1238 * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1239 * partition does not support slots.
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001240 */
Aaron Wisnerdb511202018-06-26 15:38:35 -05001241static void do_for_partitions(const std::string& part, const std::string& slot,
Daniel Zheng65452d02022-11-30 02:25:31 +00001242 const std::function<void(const std::string&)>& func,
1243 bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001244 std::string has_slot;
Yifan Hong6d7da632021-02-23 12:15:51 -08001245 // |part| can be vendor_boot:default. Query has-slot on the first token only.
1246 auto part_tokens = android::base::Split(part, ":");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001247
Daniel Rosenberg80919472016-06-30 19:25:31 -07001248 if (slot == "all") {
Yifan Hong6d7da632021-02-23 12:15:51 -08001249 if (fb->GetVar("has-slot:" + part_tokens[0], &has_slot) != fastboot::SUCCESS) {
1250 die("Could not check if partition %s has slot %s", part_tokens[0].c_str(),
1251 slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001252 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001253 if (has_slot == "yes") {
Daniel Zheng65452d02022-11-30 02:25:31 +00001254 for (int i = 0; i < get_slot_count(); i++) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001255 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001256 }
1257 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001258 do_for_partition(part, "", func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001259 }
1260 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001261 do_for_partition(part, slot, func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001262 }
1263}
1264
David Anderson0c732342018-11-28 17:10:42 -08001265static bool is_retrofit_device() {
1266 std::string value;
1267 if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1268 return false;
1269 }
1270 return android::base::StartsWith(value, "system_");
1271}
1272
Yifan Hongbcd27702021-02-16 19:37:32 -08001273// Fetch a partition from the device to a given fd. This is a wrapper over FetchToFd to fetch
1274// the full image.
1275static uint64_t fetch_partition(const std::string& partition, borrowed_fd fd) {
1276 uint64_t fetch_size = get_uint_var(FB_VAR_MAX_FETCH_SIZE);
1277 if (fetch_size == 0) {
1278 die("Unable to get %s. Device does not support fetch command.", FB_VAR_MAX_FETCH_SIZE);
1279 }
1280 uint64_t partition_size = get_partition_size(partition);
1281 if (partition_size <= 0) {
1282 die("Invalid partition size for partition %s: %" PRId64, partition.c_str(), partition_size);
1283 }
1284
1285 uint64_t offset = 0;
1286 while (offset < partition_size) {
1287 uint64_t chunk_size = std::min(fetch_size, partition_size - offset);
1288 if (fb->FetchToFd(partition, fd, offset, chunk_size) != fastboot::RetCode::SUCCESS) {
1289 die("Unable to fetch %s (offset=%" PRIx64 ", size=%" PRIx64 ")", partition.c_str(),
1290 offset, chunk_size);
1291 }
1292 offset += chunk_size;
1293 }
1294 return partition_size;
1295}
1296
1297static void do_fetch(const std::string& partition, const std::string& slot_override,
1298 const std::string& outfile) {
1299 unique_fd fd(TEMP_FAILURE_RETRY(
1300 open(outfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_BINARY, 0644)));
1301 auto fetch = std::bind(fetch_partition, _1, borrowed_fd(fd));
1302 do_for_partitions(partition, slot_override, fetch, false /* force slot */);
1303}
1304
Yifan Honge71fe242021-02-22 15:00:15 -08001305// Return immediately if not flashing a vendor boot image. If flashing a vendor boot image,
1306// repack vendor_boot image with an updated ramdisk. After execution, buf is set
1307// to the new image to flash, and return value is the real partition name to flash.
1308static std::string repack_ramdisk(const char* pname, struct fastboot_buffer* buf) {
1309 std::string_view pname_sv{pname};
1310
1311 if (!android::base::StartsWith(pname_sv, "vendor_boot:") &&
1312 !android::base::StartsWith(pname_sv, "vendor_boot_a:") &&
1313 !android::base::StartsWith(pname_sv, "vendor_boot_b:")) {
1314 return std::string(pname_sv);
1315 }
1316 if (buf->type != FB_BUFFER_FD) {
1317 die("Flashing sparse vendor ramdisk image is not supported.");
1318 }
1319 if (buf->sz <= 0) {
1320 die("repack_ramdisk() sees negative size: %" PRId64, buf->sz);
1321 }
1322 std::string partition(pname_sv.substr(0, pname_sv.find(':')));
1323 std::string ramdisk(pname_sv.substr(pname_sv.find(':') + 1));
1324
1325 unique_fd vendor_boot(make_temporary_fd("vendor boot repack"));
1326 uint64_t vendor_boot_size = fetch_partition(partition, vendor_boot);
1327 auto repack_res = replace_vendor_ramdisk(vendor_boot, vendor_boot_size, ramdisk, buf->fd,
1328 static_cast<uint64_t>(buf->sz));
1329 if (!repack_res.ok()) {
1330 die("%s", repack_res.error().message().c_str());
1331 }
1332
1333 buf->fd = std::move(vendor_boot);
1334 buf->sz = vendor_boot_size;
1335 buf->image_size = vendor_boot_size;
1336 return partition;
1337}
1338
Aaron Wisnerdb511202018-06-26 15:38:35 -05001339static void do_flash(const char* pname, const char* fname) {
Yifan Hong6d7da632021-02-23 12:15:51 -08001340 verbose("Do flash %s %s", pname, fname);
Rom Lemarchand622810c2013-06-28 09:54:59 -07001341 struct fastboot_buffer buf;
1342
Aaron Wisnerdb511202018-06-26 15:38:35 -05001343 if (!load_buf(fname, &buf)) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001344 die("cannot load '%s': %s", fname, strerror(errno));
Rom Lemarchand622810c2013-06-28 09:54:59 -07001345 }
David Anderson629e51c2018-10-25 12:51:25 -07001346 if (is_logical(pname)) {
1347 fb->ResizePartition(pname, std::to_string(buf.image_size));
1348 }
Yifan Honge71fe242021-02-22 15:00:15 -08001349 std::string flash_pname = repack_ramdisk(pname, &buf);
1350 flash_buf(flash_pname, &buf);
Colin Crossf8387882012-05-24 17:18:41 -07001351}
1352
Daniel Rosenberg13454092016-06-27 19:43:11 -07001353// Sets slot_override as the active slot. If slot_override is blank,
1354// set current slot as active instead. This clears slot-unbootable.
Aaron Wisnerdb511202018-06-26 15:38:35 -05001355static void set_active(const std::string& slot_override) {
1356 if (!supports_AB()) return;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001357
Daniel Rosenberg80919472016-06-30 19:25:31 -07001358 if (slot_override != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001359 fb->SetActive(slot_override);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001360 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001361 std::string current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001362 if (current_slot != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001363 fb->SetActive(current_slot);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001364 }
1365 }
1366}
1367
David Anderson32e376f2018-08-16 13:43:11 -07001368static bool is_userspace_fastboot() {
1369 std::string value;
Tom Cherry9027af02018-09-24 15:48:09 -07001370 return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
David Anderson32e376f2018-08-16 13:43:11 -07001371}
1372
David Anderson1d887432018-08-27 16:47:32 -07001373static void reboot_to_userspace_fastboot() {
Tom Cherry9027af02018-09-24 15:48:09 -07001374 fb->RebootTo("fastboot");
1375
1376 auto* old_transport = fb->set_transport(nullptr);
1377 delete old_transport;
David Anderson1d887432018-08-27 16:47:32 -07001378
1379 // Give the current connection time to close.
1380 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
1381
Tom Cherry9027af02018-09-24 15:48:09 -07001382 fb->set_transport(open_device());
David Anderson11d6d272018-12-07 16:39:07 -08001383
1384 if (!is_userspace_fastboot()) {
1385 die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1386 }
Hridya Valsaraju83d856e2019-05-17 14:24:19 -07001387
1388 // Reset target_sparse_limit after reboot to userspace fastboot. Max
1389 // download sizes may differ in bootloader and fastbootd.
1390 target_sparse_limit = -1;
David Anderson1d887432018-08-27 16:47:32 -07001391}
1392
David Andersonab8f4662019-10-21 16:45:59 -07001393static void CancelSnapshotIfNeeded() {
1394 std::string merge_status = "none";
1395 if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
Elliott Hughes6a7ff582020-06-05 14:06:15 -07001396 !merge_status.empty() && merge_status != "none") {
Yifan Hong712c32b2019-12-10 18:11:13 -08001397 fb->SnapshotUpdateCommand("cancel");
David Andersonab8f4662019-10-21 16:45:59 -07001398 }
1399}
1400
David Andersoncf444f32018-08-29 14:15:49 -07001401class FlashAllTool {
1402 public:
Andrew Chantd64b9882021-04-06 12:48:27 -07001403 FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary,
1404 bool wipe, bool force_flash);
David Anderson32e376f2018-08-16 13:43:11 -07001405
David Andersoncf444f32018-08-29 14:15:49 -07001406 void Flash();
David Anderson32e376f2018-08-16 13:43:11 -07001407
David Andersoncf444f32018-08-29 14:15:49 -07001408 private:
1409 void CheckRequirements();
David Anderson667b1ef2023-01-27 21:11:11 -08001410 void DetermineSlot();
David Andersoncf444f32018-08-29 14:15:49 -07001411 void CollectImages();
1412 void FlashImages(const std::vector<std::pair<const Image*, std::string>>& images);
1413 void FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf);
1414 void UpdateSuperPartition();
David Anderson667b1ef2023-01-27 21:11:11 -08001415 bool OptimizedFlashSuper();
1416
1417 // If the image uses the default slot, or the user specified "all", then
1418 // the paired string will be empty. If the image requests a specific slot
1419 // (for example, system_other) it is specified instead.
1420 using ImageEntry = std::pair<const Image*, std::string>;
1421
1422 std::string GetPartitionName(const ImageEntry& entry);
David Anderson32e376f2018-08-16 13:43:11 -07001423
David Andersoncf444f32018-08-29 14:15:49 -07001424 const ImageSource& source_;
1425 std::string slot_override_;
1426 bool skip_secondary_;
1427 bool wipe_;
Andrew Chantd64b9882021-04-06 12:48:27 -07001428 bool force_flash_;
David Anderson667b1ef2023-01-27 21:11:11 -08001429 std::string current_slot_;
David Andersoncf444f32018-08-29 14:15:49 -07001430 std::string secondary_slot_;
David Anderson667b1ef2023-01-27 21:11:11 -08001431
1432 std::vector<ImageEntry> boot_images_;
1433 std::vector<ImageEntry> os_images_;
David Andersoncf444f32018-08-29 14:15:49 -07001434};
1435
Andrew Chantd64b9882021-04-06 12:48:27 -07001436FlashAllTool::FlashAllTool(const ImageSource& source, const std::string& slot_override,
1437 bool skip_secondary, bool wipe, bool force_flash)
Daniel Zheng65452d02022-11-30 02:25:31 +00001438 : source_(source),
1439 slot_override_(slot_override),
1440 skip_secondary_(skip_secondary),
1441 wipe_(wipe),
1442 force_flash_(force_flash) {}
David Anderson32e376f2018-08-16 13:43:11 -07001443
David Andersoncf444f32018-08-29 14:15:49 -07001444void FlashAllTool::Flash() {
Tom Cherry9027af02018-09-24 15:48:09 -07001445 DumpInfo();
David Andersoncf444f32018-08-29 14:15:49 -07001446 CheckRequirements();
David Anderson96a9fd42018-11-05 15:21:44 -08001447
1448 // Change the slot first, so we boot into the correct recovery image when
1449 // using fastbootd.
1450 if (slot_override_ == "all") {
1451 set_active("a");
1452 } else {
1453 set_active(slot_override_);
1454 }
1455
David Anderson667b1ef2023-01-27 21:11:11 -08001456 DetermineSlot();
David Andersoncf444f32018-08-29 14:15:49 -07001457 CollectImages();
David Anderson32e376f2018-08-16 13:43:11 -07001458
David Andersonab8f4662019-10-21 16:45:59 -07001459 CancelSnapshotIfNeeded();
1460
David Anderson95d40932018-08-28 12:14:33 -07001461 // First flash boot partitions. We allow this to happen either in userspace
1462 // or in bootloader fastboot.
David Andersoncf444f32018-08-29 14:15:49 -07001463 FlashImages(boot_images_);
David Anderson95d40932018-08-28 12:14:33 -07001464
David Anderson667b1ef2023-01-27 21:11:11 -08001465 if (!OptimizedFlashSuper()) {
1466 // Sync the super partition. This will reboot to userspace fastboot if needed.
1467 UpdateSuperPartition();
David Anderson95d40932018-08-28 12:14:33 -07001468
David Anderson667b1ef2023-01-27 21:11:11 -08001469 // Resize any logical partition to 0, so each partition is reset to 0
1470 // extents, and will achieve more optimal allocation.
1471 for (const auto& [image, slot] : os_images_) {
1472 auto resize_partition = [](const std::string& partition) -> void {
1473 if (is_logical(partition)) {
1474 fb->ResizePartition(partition, "0");
1475 }
1476 };
1477 do_for_partitions(image->part_name, slot, resize_partition, false);
1478 }
David Anderson32e376f2018-08-16 13:43:11 -07001479 }
1480
David Anderson95d40932018-08-28 12:14:33 -07001481 // Flash OS images, resizing logical partitions as needed.
David Andersoncf444f32018-08-29 14:15:49 -07001482 FlashImages(os_images_);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001483}
1484
David Anderson667b1ef2023-01-27 21:11:11 -08001485bool FlashAllTool::OptimizedFlashSuper() {
1486 if (!supports_AB()) {
1487 LOG(VERBOSE) << "Cannot optimize flashing super on non-AB device";
1488 return false;
1489 }
1490 if (slot_override_ == "all") {
1491 LOG(VERBOSE) << "Cannot optimize flashing super for all slots";
1492 return false;
1493 }
1494
1495 // Does this device use dynamic partitions at all?
1496 unique_fd fd = source_.OpenFile("super_empty.img");
1497 if (fd < 0) {
1498 LOG(VERBOSE) << "could not open super_empty.img";
1499 return false;
1500 }
1501
1502 // Try to find whether there is a super partition.
1503 std::string super_name;
1504 if (fb->GetVar("super-partition-name", &super_name) != fastboot::SUCCESS) {
1505 super_name = "super";
1506 }
1507 std::string partition_size_str;
1508 if (fb->GetVar("partition-size:" + super_name, &partition_size_str) != fastboot::SUCCESS) {
1509 LOG(VERBOSE) << "Cannot optimize super flashing: could not determine super partition";
1510 return false;
1511 }
1512
1513 SuperFlashHelper helper(source_);
1514 if (!helper.Open(fd)) {
1515 return false;
1516 }
1517
1518 for (const auto& entry : os_images_) {
1519 auto partition = GetPartitionName(entry);
1520 auto image = entry.first;
1521
1522 if (!helper.AddPartition(partition, image->img_name, image->optional_if_no_image)) {
1523 return false;
1524 }
1525 }
1526
1527 auto s = helper.GetSparseLayout();
1528 if (!s) {
1529 return false;
1530 }
1531
1532 std::vector<SparsePtr> files;
1533 if (int limit = get_sparse_limit(sparse_file_len(s.get(), false, false))) {
1534 files = resparse_file(s.get(), limit);
1535 } else {
1536 files.emplace_back(std::move(s));
1537 }
1538
1539 // Send the data to the device.
1540 flash_partition_files(super_name, files);
1541
1542 // Remove images that we already flashed, just in case we have non-dynamic OS images.
1543 auto remove_if_callback = [&, this](const ImageEntry& entry) -> bool {
1544 return helper.WillFlash(GetPartitionName(entry));
1545 };
1546 os_images_.erase(std::remove_if(os_images_.begin(), os_images_.end(), remove_if_callback),
1547 os_images_.end());
1548 return true;
1549}
1550
David Andersoncf444f32018-08-29 14:15:49 -07001551void FlashAllTool::CheckRequirements() {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001552 std::vector<char> contents;
1553 if (!source_.ReadFile("android-info.txt", &contents)) {
David Andersoncf444f32018-08-29 14:15:49 -07001554 die("could not read android-info.txt");
1555 }
Andrew Chantd64b9882021-04-06 12:48:27 -07001556 ::CheckRequirements({contents.data(), contents.size()}, force_flash_);
David Andersoncf444f32018-08-29 14:15:49 -07001557}
1558
David Anderson667b1ef2023-01-27 21:11:11 -08001559void FlashAllTool::DetermineSlot() {
1560 if (slot_override_.empty()) {
1561 current_slot_ = get_current_slot();
1562 } else {
1563 current_slot_ = slot_override_;
1564 }
1565
David Andersoncf444f32018-08-29 14:15:49 -07001566 if (skip_secondary_) {
1567 return;
1568 }
David Anderson96a9fd42018-11-05 15:21:44 -08001569 if (slot_override_ != "" && slot_override_ != "all") {
David Andersoncf444f32018-08-29 14:15:49 -07001570 secondary_slot_ = get_other_slot(slot_override_);
1571 } else {
1572 secondary_slot_ = get_other_slot();
1573 }
1574 if (secondary_slot_ == "") {
1575 if (supports_AB()) {
1576 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1577 }
1578 skip_secondary_ = true;
1579 }
1580}
1581
1582void FlashAllTool::CollectImages() {
Daniel Zheng65452d02022-11-30 02:25:31 +00001583 for (size_t i = 0; i < images.size(); ++i) {
David Andersoncf444f32018-08-29 14:15:49 -07001584 std::string slot = slot_override_;
1585 if (images[i].IsSecondary()) {
1586 if (skip_secondary_) {
1587 continue;
1588 }
1589 slot = secondary_slot_;
1590 }
1591 if (images[i].type == ImageType::BootCritical) {
1592 boot_images_.emplace_back(&images[i], slot);
1593 } else if (images[i].type == ImageType::Normal) {
1594 os_images_.emplace_back(&images[i], slot);
1595 }
1596 }
1597}
1598
1599void FlashAllTool::FlashImages(const std::vector<std::pair<const Image*, std::string>>& images) {
1600 for (const auto& [image, slot] : images) {
1601 fastboot_buffer buf;
Yifan Hongb10d0672021-02-22 15:06:27 -08001602 unique_fd fd = source_.OpenFile(image->img_name);
1603 if (fd < 0 || !load_buf_fd(std::move(fd), &buf)) {
David Andersoncf444f32018-08-29 14:15:49 -07001604 if (image->optional_if_no_image) {
1605 continue;
1606 }
Daniel Zheng65452d02022-11-30 02:25:31 +00001607 die("could not load '%s': %s", image->img_name.c_str(), strerror(errno));
David Andersoncf444f32018-08-29 14:15:49 -07001608 }
1609 FlashImage(*image, slot, &buf);
1610 }
1611}
1612
1613void FlashAllTool::FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf) {
1614 auto flash = [&, this](const std::string& partition_name) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001615 std::vector<char> signature_data;
1616 if (source_.ReadFile(image.sig_name, &signature_data)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001617 fb->Download("signature", signature_data);
1618 fb->RawCommand("signature", "installing signature");
David Andersoncf444f32018-08-29 14:15:49 -07001619 }
1620
1621 if (is_logical(partition_name)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001622 fb->ResizePartition(partition_name, std::to_string(buf->image_size));
David Andersoncf444f32018-08-29 14:15:49 -07001623 }
1624 flash_buf(partition_name.c_str(), buf);
1625 };
1626 do_for_partitions(image.part_name, slot, flash, false);
1627}
1628
1629void FlashAllTool::UpdateSuperPartition() {
Yifan Hong58532df2021-03-22 16:39:13 -07001630 unique_fd fd = source_.OpenFile("super_empty.img");
David Andersoncf444f32018-08-29 14:15:49 -07001631 if (fd < 0) {
1632 return;
1633 }
1634 if (!is_userspace_fastboot()) {
1635 reboot_to_userspace_fastboot();
1636 }
David Andersoncf444f32018-08-29 14:15:49 -07001637
David Anderson90fe0a42018-11-05 18:01:32 -08001638 std::string super_name;
1639 if (fb->GetVar("super-partition-name", &super_name) != fastboot::RetCode::SUCCESS) {
1640 super_name = "super";
1641 }
1642 fb->Download(super_name, fd, get_file_size(fd));
1643
1644 std::string command = "update-super:" + super_name;
David Andersoncf444f32018-08-29 14:15:49 -07001645 if (wipe_) {
1646 command += ":wipe";
1647 }
Tom Cherry9027af02018-09-24 15:48:09 -07001648 fb->RawCommand(command, "Updating super partition");
David Anderson0c732342018-11-28 17:10:42 -08001649
1650 // Retrofit devices have two super partitions, named super_a and super_b.
1651 // On these devices, secondary slots must be flashed as physical
1652 // partitions (otherwise they would not mount on first boot). To enforce
1653 // this, we delete any logical partitions for the "other" slot.
1654 if (is_retrofit_device()) {
1655 for (const auto& [image, slot] : os_images_) {
1656 std::string partition_name = image->part_name + "_"s + slot;
1657 if (image->IsSecondary() && is_logical(partition_name)) {
1658 fb->DeletePartition(partition_name);
1659 }
1660 }
1661 }
David Andersoncf444f32018-08-29 14:15:49 -07001662}
1663
David Anderson667b1ef2023-01-27 21:11:11 -08001664std::string FlashAllTool::GetPartitionName(const ImageEntry& entry) {
1665 auto slot = entry.second;
1666 if (slot.empty()) {
1667 slot = current_slot_;
1668 }
1669 if (slot.empty()) {
1670 return entry.first->part_name;
1671 }
1672 if (slot == "all") {
1673 LOG(FATAL) << "Cannot retrieve a singular name when using all slots";
1674 }
1675 return entry.first->part_name + "_" + slot;
1676}
1677
David Andersoncf444f32018-08-29 14:15:49 -07001678class ZipImageSource final : public ImageSource {
1679 public:
1680 explicit ZipImageSource(ZipArchiveHandle zip) : zip_(zip) {}
Tom Cherrydfd85df2018-09-20 14:45:05 -07001681 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
Yifan Hongb10d0672021-02-22 15:06:27 -08001682 unique_fd OpenFile(const std::string& name) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001683
1684 private:
1685 ZipArchiveHandle zip_;
1686};
1687
Tom Cherrydfd85df2018-09-20 14:45:05 -07001688bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1689 return UnzipToMemory(zip_, name, out);
David Andersoncf444f32018-08-29 14:15:49 -07001690}
1691
Yifan Hongb10d0672021-02-22 15:06:27 -08001692unique_fd ZipImageSource::OpenFile(const std::string& name) const {
David Andersoncf444f32018-08-29 14:15:49 -07001693 return unzip_to_file(zip_, name.c_str());
1694}
1695
Andrew Chantd64b9882021-04-06 12:48:27 -07001696static void do_update(const char* filename, const std::string& slot_override, bool skip_secondary,
1697 bool force_flash) {
David Andersoncf444f32018-08-29 14:15:49 -07001698 ZipArchiveHandle zip;
1699 int error = OpenArchive(filename, &zip);
1700 if (error != 0) {
1701 die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1702 }
1703
Andrew Chantd64b9882021-04-06 12:48:27 -07001704 FlashAllTool tool(ZipImageSource(zip), slot_override, skip_secondary, false, force_flash);
David Andersoncf444f32018-08-29 14:15:49 -07001705 tool.Flash();
1706
1707 CloseArchive(zip);
1708}
1709
1710class LocalImageSource final : public ImageSource {
1711 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001712 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
Yifan Hongb10d0672021-02-22 15:06:27 -08001713 unique_fd OpenFile(const std::string& name) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001714};
1715
Tom Cherrydfd85df2018-09-20 14:45:05 -07001716bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
David Andersoncf444f32018-08-29 14:15:49 -07001717 auto path = find_item_given_name(name);
1718 if (path.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001719 return false;
David Andersoncf444f32018-08-29 14:15:49 -07001720 }
Tom Cherrydfd85df2018-09-20 14:45:05 -07001721 return ReadFileToVector(path, out);
David Andersoncf444f32018-08-29 14:15:49 -07001722}
1723
Yifan Hongb10d0672021-02-22 15:06:27 -08001724unique_fd LocalImageSource::OpenFile(const std::string& name) const {
David Andersoncf444f32018-08-29 14:15:49 -07001725 auto path = find_item_given_name(name);
Yifan Hongb10d0672021-02-22 15:06:27 -08001726 return unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_BINARY)));
David Andersoncf444f32018-08-29 14:15:49 -07001727}
1728
Andrew Chantd64b9882021-04-06 12:48:27 -07001729static void do_flashall(const std::string& slot_override, bool skip_secondary, bool wipe,
1730 bool force_flash) {
1731 FlashAllTool tool(LocalImageSource(), slot_override, skip_secondary, wipe, force_flash);
David Andersoncf444f32018-08-29 14:15:49 -07001732 tool.Flash();
1733}
1734
Elliott Hughesd6365a72017-05-08 18:04:49 -07001735static std::string next_arg(std::vector<std::string>* args) {
1736 if (args->empty()) syntax_error("expected argument");
1737 std::string result = args->front();
1738 args->erase(args->begin());
1739 return result;
Patrick Tjin51e8b032015-09-01 08:15:23 -07001740}
1741
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001742static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001743 if (args->empty()) syntax_error("empty oem command");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001744
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001745 std::string command(cmd);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001746 while (!args->empty()) {
Elliott Hughes29d5d7d2017-05-11 15:05:13 -07001747 command += " " + next_arg(args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001748 }
Tom Cherry9027af02018-09-24 15:48:09 -07001749 fb->RawCommand(command, "");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001750}
1751
Aaron Wisnerdb511202018-06-26 15:38:35 -05001752static unsigned fb_get_flash_block_size(std::string name) {
Connor O'Brience16a8a2017-02-06 14:39:31 -08001753 std::string sizeString;
Tom Cherry9027af02018-09-24 15:48:09 -07001754 if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001755 // This device does not report flash block sizes, so return 0.
Connor O'Brience16a8a2017-02-06 14:39:31 -08001756 return 0;
1757 }
1758 sizeString = fb_fix_numeric_var(sizeString);
1759
1760 unsigned size;
1761 if (!android::base::ParseUint(sizeString, &size)) {
1762 fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1763 return 0;
1764 }
Connor O'Brien6ef5c242017-11-01 17:37:32 -07001765 if ((size & (size - 1)) != 0) {
1766 fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
Connor O'Brience16a8a2017-02-06 14:39:31 -08001767 return 0;
1768 }
1769 return size;
1770}
1771
ThiƩbaud Weksteen5d72d6c2022-07-21 14:43:20 +10001772static void fb_perform_format(const std::string& partition, int skip_if_not_supported,
Elliott Hughesd6365a72017-05-08 18:04:49 -07001773 const std::string& type_override, const std::string& size_override,
ThiƩbaud Weksteen5d72d6c2022-07-21 14:43:20 +10001774 const unsigned fs_options) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001775 std::string partition_type, partition_size;
1776
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001777 struct fastboot_buffer buf;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001778 const char* errMsg = nullptr;
1779 const struct fs_generator* gen = nullptr;
Jin Qian4a335822017-04-18 16:23:18 -07001780 TemporaryFile output;
1781 unique_fd fd;
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001782
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001783 unsigned int limit = INT_MAX;
1784 if (target_sparse_limit > 0 && target_sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001785 limit = target_sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001786 }
1787 if (sparse_limit > 0 && sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001788 limit = sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001789 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001790
Tom Cherry9027af02018-09-24 15:48:09 -07001791 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001792 errMsg = "Can't determine partition type.\n";
1793 goto failed;
1794 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001795 if (!type_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001796 if (partition_type != type_override) {
1797 fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001798 partition.c_str(), partition_type.c_str(), type_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001799 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001800 partition_type = type_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001801 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001802
Tom Cherry9027af02018-09-24 15:48:09 -07001803 if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001804 errMsg = "Unable to get partition size\n";
1805 goto failed;
1806 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001807 if (!size_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001808 if (partition_size != size_override) {
1809 fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001810 partition.c_str(), partition_size.c_str(), size_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001811 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001812 partition_size = size_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001813 }
Connor O'Brience16a8a2017-02-06 14:39:31 -08001814 partition_size = fb_fix_numeric_var(partition_size);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001815
Elliott Hughes8ab9a322015-11-02 14:05:57 -08001816 gen = fs_get_generator(partition_type);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001817 if (!gen) {
1818 if (skip_if_not_supported) {
1819 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001820 fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001821 return;
1822 }
Daniel Zheng65452d02022-11-30 02:25:31 +00001823 die("Formatting is not supported for file system with type '%s'.", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001824 }
1825
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001826 int64_t size;
Elliott Hughesda46b392016-10-11 17:09:00 -07001827 if (!android::base::ParseInt(partition_size, &size)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001828 die("Couldn't parse partition size '%s'.", partition_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001829 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001830
Connor O'Brience16a8a2017-02-06 14:39:31 -08001831 unsigned eraseBlkSize, logicalBlkSize;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001832 eraseBlkSize = fb_get_flash_block_size("erase-block-size");
1833 logicalBlkSize = fb_get_flash_block_size("logical-block-size");
Connor O'Brience16a8a2017-02-06 14:39:31 -08001834
ThiƩbaud Weksteen5d72d6c2022-07-21 14:43:20 +10001835 if (fs_generator_generate(gen, output.path, size, eraseBlkSize, logicalBlkSize, fs_options)) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001836 die("Cannot generate image for %s", partition.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001837 }
1838
Jin Qian4a335822017-04-18 16:23:18 -07001839 fd.reset(open(output.path, O_RDONLY));
1840 if (fd == -1) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001841 die("Cannot open generated image: %s", strerror(errno));
Jin Qian4a335822017-04-18 16:23:18 -07001842 }
Yifan Hongb10d0672021-02-22 15:06:27 -08001843 if (!load_buf_fd(std::move(fd), &buf)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001844 die("Cannot read image: %s", strerror(errno));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001845 }
1846 flash_buf(partition, &buf);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001847 return;
1848
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001849failed:
1850 if (skip_if_not_supported) {
1851 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001852 if (errMsg) fprintf(stderr, "%s", errMsg);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001853 }
Tom Cherry9027af02018-09-24 15:48:09 -07001854 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
Mark Salyzyna30b6962018-11-20 11:04:15 -08001855 if (!skip_if_not_supported) {
1856 die("Command failed");
1857 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001858}
1859
David Anderson89569642018-11-16 15:53:35 -08001860static bool should_flash_in_userspace(const std::string& partition_name) {
David Andersone0e693c2018-11-27 20:19:26 -08001861 if (!get_android_product_out()) {
1862 return false;
1863 }
David Anderson89569642018-11-16 15:53:35 -08001864 auto path = find_item_given_name("super_empty.img");
David Anderson00475802018-12-04 17:05:47 -08001865 if (path.empty() || access(path.c_str(), R_OK)) {
David Anderson89569642018-11-16 15:53:35 -08001866 return false;
1867 }
1868 auto metadata = android::fs_mgr::ReadFromImageFile(path);
1869 if (!metadata) {
1870 return false;
1871 }
David Andersonaa87dc52023-01-27 20:39:06 -08001872 return should_flash_in_userspace(*metadata.get(), partition_name);
David Anderson89569642018-11-16 15:53:35 -08001873}
1874
David Anderson7c84b9f2019-06-27 22:15:29 -07001875static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
1876 std::string* message) {
1877 auto super_device = GetMetadataSuperBlockDevice(metadata);
1878 auto block_size = metadata.geometry.logical_block_size;
1879 auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
1880
1881 if (super_bdev_name != "super") {
1882 // retrofit devices do not allow flashing to the retrofit partitions,
1883 // so enable it if we can.
1884 fb->RawCommand("oem allow-flash-super");
1885 }
1886
1887 // Note: do not use die() in here, since we want TemporaryDir's destructor
1888 // to be called.
1889 TemporaryDir temp_dir;
1890
1891 bool ok;
1892 if (metadata.block_devices.size() > 1) {
1893 ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
1894 } else {
1895 auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
1896 ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
1897 }
1898 if (!ok) {
1899 *message = "Could not generate a flashable super image file";
1900 return false;
1901 }
1902
1903 for (const auto& block_device : metadata.block_devices) {
1904 auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
1905 bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
1906
1907 std::string image_name;
1908 if (metadata.block_devices.size() > 1) {
1909 image_name = "super_" + partition + ".img";
1910 } else {
1911 image_name = partition + ".img";
1912 }
1913
1914 auto image_path = temp_dir.path + "/"s + image_name;
1915 auto flash = [&](const std::string& partition_name) {
1916 do_flash(partition_name.c_str(), image_path.c_str());
1917 };
1918 do_for_partitions(partition, slot, flash, force_slot);
1919
1920 unlink(image_path.c_str());
1921 }
1922 return true;
1923}
1924
1925static void do_wipe_super(const std::string& image, const std::string& slot_override) {
1926 if (access(image.c_str(), R_OK) != 0) {
1927 die("Could not read image: %s", image.c_str());
1928 }
1929 auto metadata = android::fs_mgr::ReadFromImageFile(image);
1930 if (!metadata) {
1931 die("Could not parse image: %s", image.c_str());
1932 }
1933
1934 auto slot = slot_override;
1935 if (slot.empty()) {
1936 slot = get_current_slot();
1937 }
1938
1939 std::string message;
1940 if (!wipe_super(*metadata.get(), slot, &message)) {
1941 die(message);
1942 }
1943}
1944
David Andersona67fc322023-01-27 16:15:52 -08001945static void FastbootLogger(android::base::LogId /* id */, android::base::LogSeverity /* severity */,
1946 const char* /* tag */, const char* /* file */, unsigned int /* line */,
1947 const char* message) {
1948 verbose("%s", message);
1949}
1950
1951static void FastbootAborter(const char* message) {
1952 die("%s", message);
1953}
1954
Aaron Wisnerdb511202018-06-26 15:38:35 -05001955int FastBootTool::Main(int argc, char* argv[]) {
David Andersona67fc322023-01-27 16:15:52 -08001956 android::base::InitLogging(argv, FastbootLogger, FastbootAborter);
1957
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001958 bool wants_wipe = false;
1959 bool wants_reboot = false;
1960 bool wants_reboot_bootloader = false;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001961 bool wants_reboot_recovery = false;
1962 bool wants_reboot_fastboot = false;
Mitchell Wills31dce302016-09-26 10:26:21 -07001963 bool skip_reboot = false;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001964 bool wants_set_active = false;
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001965 bool skip_secondary = false;
David Anderson89569642018-11-16 15:53:35 -08001966 bool force_flash = false;
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08001967 unsigned fs_options = 0;
Florian BƤuerle27ded482014-11-24 11:29:34 +01001968 int longindex;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001969 std::string slot_override;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001970 std::string next_active;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001971
Elliott Hughes577e8b42018-04-05 16:12:47 -07001972 g_boot_img_hdr.kernel_addr = 0x00008000;
1973 g_boot_img_hdr.ramdisk_addr = 0x01000000;
1974 g_boot_img_hdr.second_addr = 0x00f00000;
1975 g_boot_img_hdr.tags_addr = 0x00000100;
1976 g_boot_img_hdr.page_size = 2048;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001977 g_boot_img_hdr.dtb_addr = 0x01100000;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001978
Daniel Zheng65452d02022-11-30 02:25:31 +00001979 const struct option longopts[] = {{"base", required_argument, 0, 0},
1980 {"cmdline", required_argument, 0, 0},
1981 {"disable-verification", no_argument, 0, 0},
1982 {"disable-verity", no_argument, 0, 0},
1983 {"force", no_argument, 0, 0},
1984 {"fs-options", required_argument, 0, 0},
1985 {"header-version", required_argument, 0, 0},
1986 {"help", no_argument, 0, 'h'},
1987 {"kernel-offset", required_argument, 0, 0},
1988 {"os-patch-level", required_argument, 0, 0},
1989 {"os-version", required_argument, 0, 0},
1990 {"page-size", required_argument, 0, 0},
1991 {"ramdisk-offset", required_argument, 0, 0},
1992 {"set-active", optional_argument, 0, 'a'},
1993 {"skip-reboot", no_argument, 0, 0},
1994 {"skip-secondary", no_argument, 0, 0},
1995 {"slot", required_argument, 0, 0},
1996 {"tags-offset", required_argument, 0, 0},
1997 {"dtb", required_argument, 0, 0},
1998 {"dtb-offset", required_argument, 0, 0},
1999 {"unbuffered", no_argument, 0, 0},
2000 {"verbose", no_argument, 0, 'v'},
2001 {"version", no_argument, 0, 0},
2002 {0, 0, 0, 0}};
Colin Cross8879f982012-05-22 17:53:34 -07002003
2004 serial = getenv("ANDROID_SERIAL");
2005
Elliott Hughes577e8b42018-04-05 16:12:47 -07002006 int c;
Elliott Hughesf3192bd2018-04-10 15:38:08 -07002007 while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
Elliott Hughes577e8b42018-04-05 16:12:47 -07002008 if (c == 0) {
2009 std::string name{longopts[longindex].name};
2010 if (name == "base") {
2011 g_base_addr = strtoul(optarg, 0, 16);
2012 } else if (name == "cmdline") {
2013 g_cmdline = optarg;
2014 } else if (name == "disable-verification") {
2015 g_disable_verification = true;
2016 } else if (name == "disable-verity") {
2017 g_disable_verity = true;
David Anderson89569642018-11-16 15:53:35 -08002018 } else if (name == "force") {
2019 force_flash = true;
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002020 } else if (name == "fs-options") {
2021 fs_options = ParseFsOption(optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002022 } else if (name == "header-version") {
2023 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08002024 } else if (name == "dtb") {
2025 g_dtb_path = optarg;
Elliott Hughes577e8b42018-04-05 16:12:47 -07002026 } else if (name == "kernel-offset") {
2027 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
2028 } else if (name == "os-patch-level") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002029 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002030 } else if (name == "os-version") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002031 ParseOsVersion(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002032 } else if (name == "page-size") {
2033 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
2034 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
2035 } else if (name == "ramdisk-offset") {
2036 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
2037 } else if (name == "skip-reboot") {
2038 skip_reboot = true;
2039 } else if (name == "skip-secondary") {
2040 skip_secondary = true;
2041 } else if (name == "slot") {
2042 slot_override = optarg;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08002043 } else if (name == "dtb-offset") {
2044 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002045 } else if (name == "tags-offset") {
2046 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
2047 } else if (name == "unbuffered") {
Elliott Hughesfc797672015-04-07 20:12:50 -07002048 setvbuf(stdout, nullptr, _IONBF, 0);
2049 setvbuf(stderr, nullptr, _IONBF, 0);
Elliott Hughes577e8b42018-04-05 16:12:47 -07002050 } else if (name == "version") {
Daniel Zheng65452d02022-11-30 02:25:31 +00002051 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION,
2052 android::build::GetBuildNumber().c_str());
Elliott Hughes1fd46df2017-03-30 15:08:28 -07002053 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
Elliott Hughes379646b2015-06-02 13:50:00 -07002054 return 0;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00002055 } else {
Elliott Hughes855cdf82018-04-02 14:24:03 -07002056 die("unknown option %s", longopts[longindex].name);
Florian BƤuerle27ded482014-11-24 11:29:34 +01002057 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07002058 } else {
2059 switch (c) {
2060 case 'a':
2061 wants_set_active = true;
2062 if (optarg) next_active = optarg;
2063 break;
2064 case 'h':
2065 return show_help();
Elliott Hughes577e8b42018-04-05 16:12:47 -07002066 case 'l':
2067 g_long_listing = true;
2068 break;
2069 case 's':
2070 serial = optarg;
2071 break;
2072 case 'S':
Elliott Hughes542370d2018-04-19 19:49:44 -07002073 if (!android::base::ParseByteCount(optarg, &sparse_limit)) {
2074 die("invalid sparse limit %s", optarg);
2075 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07002076 break;
2077 case 'v':
2078 set_verbose();
2079 break;
2080 case 'w':
2081 wants_wipe = true;
2082 break;
2083 case '?':
2084 return 1;
2085 default:
2086 abort();
2087 }
Colin Cross8879f982012-05-22 17:53:34 -07002088 }
2089 }
2090
2091 argc -= optind;
2092 argv += optind;
2093
Elliott Hughesd6365a72017-05-08 18:04:49 -07002094 if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002095
Colin Cross8fb6e062012-07-24 16:36:41 -07002096 if (argc > 0 && !strcmp(*argv, "devices")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002097 list_devices();
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08002098 return 0;
2099 }
2100
Colin Crossc7b75dc2012-08-29 18:17:06 -07002101 if (argc > 0 && !strcmp(*argv, "help")) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002102 return show_help();
Colin Crossc7b75dc2012-08-29 18:17:06 -07002103 }
2104
David Pursell0b156632015-10-30 11:22:01 -07002105 Transport* transport = open_device();
David Pursell2ec418a2016-01-20 08:32:08 -08002106 if (transport == nullptr) {
2107 return 1;
2108 }
Tom Cherry9027af02018-09-24 15:48:09 -07002109 fastboot::DriverCallbacks driver_callbacks = {
Daniel Zheng65452d02022-11-30 02:25:31 +00002110 .prolog = Status,
2111 .epilog = Epilog,
2112 .info = InfoMessage,
Tom Cherry9027af02018-09-24 15:48:09 -07002113 };
2114 fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
2115 fb = &fastboot_driver;
David Pursell2ec418a2016-01-20 08:32:08 -08002116
Elliott Hughes5620d222018-03-28 08:20:00 -07002117 const double start = now();
2118
Aaron Wisnerdb511202018-06-26 15:38:35 -05002119 if (slot_override != "") slot_override = verify_slot(slot_override);
2120 if (next_active != "") next_active = verify_slot(next_active, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002121
2122 if (wants_set_active) {
2123 if (next_active == "") {
2124 if (slot_override == "") {
Daniel Rosenberg13454092016-06-27 19:43:11 -07002125 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07002126 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
LuK1337dae48ef2020-04-06 14:38:58 +02002127 if (current_slot[0] == '_') current_slot.erase(0, 1);
Aaron Wisnerdb511202018-06-26 15:38:35 -05002128 next_active = verify_slot(current_slot, false);
Daniel Rosenberg13454092016-06-27 19:43:11 -07002129 } else {
2130 wants_set_active = false;
2131 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002132 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002133 next_active = verify_slot(slot_override, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002134 }
2135 }
2136 }
Elliott Hughes31dbed72009-10-07 15:38:53 -07002137
Elliott Hughesd6365a72017-05-08 18:04:49 -07002138 std::vector<std::string> args(argv, argv + argc);
2139 while (!args.empty()) {
2140 std::string command = next_arg(&args);
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002141
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002142 if (command == FB_CMD_GETVAR) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002143 std::string variable = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002144 DisplayVarOrError(variable, variable);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002145 } else if (command == FB_CMD_ERASE) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002146 std::string partition = next_arg(&args);
2147 auto erase = [&](const std::string& partition) {
David Pursell0b156632015-10-30 11:22:01 -07002148 std::string partition_type;
Daniel Zheng65452d02022-11-30 02:25:31 +00002149 if (fb->GetVar("partition-type:" + partition, &partition_type) ==
2150 fastboot::SUCCESS &&
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002151 fs_get_generator(partition_type) != nullptr) {
2152 fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
2153 partition_type.c_str());
2154 }
Ken Sumrall5ee5d382012-09-29 14:46:25 -07002155
Tom Cherry9027af02018-09-24 15:48:09 -07002156 fb->Erase(partition);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002157 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05002158 do_for_partitions(partition, slot_override, erase, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002159 } else if (android::base::StartsWith(command, "format")) {
2160 // Parsing for: "format[:[type][:[size]]]"
2161 // Some valid things:
2162 // - select only the size, and leave default fs type:
2163 // format::0x4000000 userdata
2164 // - default fs type and size:
2165 // format userdata
2166 // format:: userdata
2167 std::vector<std::string> pieces = android::base::Split(command, ":");
2168 std::string type_override;
2169 if (pieces.size() > 1) type_override = pieces[1].c_str();
2170 std::string size_override;
2171 if (pieces.size() > 2) size_override = pieces[2].c_str();
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002172
Elliott Hughesd6365a72017-05-08 18:04:49 -07002173 std::string partition = next_arg(&args);
2174
2175 auto format = [&](const std::string& partition) {
ThiƩbaud Weksteen5d72d6c2022-07-21 14:43:20 +10002176 fb_perform_format(partition, 0, type_override, size_override, fs_options);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002177 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07002178 do_for_partitions(partition, slot_override, format, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002179 } else if (command == "signature") {
2180 std::string filename = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002181 std::vector<char> data;
2182 if (!ReadFileToVector(filename, &data)) {
2183 die("could not load '%s': %s", filename.c_str(), strerror(errno));
2184 }
2185 if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
Tom Cherry9027af02018-09-24 15:48:09 -07002186 fb->Download("signature", data);
2187 fb->RawCommand("signature", "installing signature");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002188 } else if (command == FB_CMD_REBOOT) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002189 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002190
2191 if (args.size() == 1) {
2192 std::string what = next_arg(&args);
2193 if (what == "bootloader") {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002194 wants_reboot = false;
2195 wants_reboot_bootloader = true;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002196 } else if (what == "recovery") {
2197 wants_reboot = false;
2198 wants_reboot_recovery = true;
2199 } else if (what == "fastboot") {
2200 wants_reboot = false;
2201 wants_reboot_fastboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002202 } else {
2203 syntax_error("unknown reboot target %s", what.c_str());
Alexey Polyudove0bfb752017-01-03 19:39:13 -08002204 }
Elliott Hughesca85df02015-02-25 10:02:00 -08002205 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002206 if (!args.empty()) syntax_error("junk after reboot command");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002207 } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002208 wants_reboot_bootloader = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002209 } else if (command == FB_CMD_REBOOT_RECOVERY) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002210 wants_reboot_recovery = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002211 } else if (command == FB_CMD_REBOOT_FASTBOOT) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002212 wants_reboot_fastboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002213 } else if (command == FB_CMD_CONTINUE) {
Tom Cherry9027af02018-09-24 15:48:09 -07002214 fb->Continue();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002215 } else if (command == FB_CMD_BOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002216 std::string kernel = next_arg(&args);
2217 std::string ramdisk;
2218 if (!args.empty()) ramdisk = next_arg(&args);
2219 std::string second_stage;
2220 if (!args.empty()) second_stage = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07002221 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
Tom Cherry9027af02018-09-24 15:48:09 -07002222 fb->Download("boot.img", data);
2223 fb->Boot();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002224 } else if (command == FB_CMD_FLASH) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002225 std::string pname = next_arg(&args);
2226
Elliott Hughes2810d002016-04-25 14:31:18 -07002227 std::string fname;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002228 if (!args.empty()) {
2229 fname = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002230 } else {
Elliott Hughes45964a82017-05-03 22:43:23 -07002231 fname = find_item(pname);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002232 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002233 if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002234
Daniel Zheng65452d02022-11-30 02:25:31 +00002235 auto flash = [&](const std::string& partition) {
David Anderson89569642018-11-16 15:53:35 -08002236 if (should_flash_in_userspace(partition) && !is_userspace_fastboot() &&
2237 !force_flash) {
2238 die("The partition you are trying to flash is dynamic, and "
2239 "should be flashed via fastbootd. Please run:\n"
2240 "\n"
2241 " fastboot reboot fastboot\n"
2242 "\n"
2243 "And try again. If you are intentionally trying to "
2244 "overwrite a fixed partition, use --force.");
2245 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05002246 do_flash(partition.c_str(), fname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002247 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07002248 do_for_partitions(pname, slot_override, flash, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002249 } else if (command == "flash:raw") {
2250 std::string partition = next_arg(&args);
2251 std::string kernel = next_arg(&args);
2252 std::string ramdisk;
2253 if (!args.empty()) ramdisk = next_arg(&args);
2254 std::string second_stage;
2255 if (!args.empty()) second_stage = next_arg(&args);
2256
Tom Cherrydfd85df2018-09-20 14:45:05 -07002257 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
2258 auto flashraw = [&data](const std::string& partition) {
Tom Cherry9027af02018-09-24 15:48:09 -07002259 fb->FlashPartition(partition, data);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07002260 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05002261 do_for_partitions(partition, slot_override, flashraw, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002262 } else if (command == "flashall") {
Alex Lightbb9b8a52016-06-29 09:26:44 -07002263 if (slot_override == "all") {
Daniel Zheng65452d02022-11-30 02:25:31 +00002264 fprintf(stderr,
2265 "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
Andrew Chantd64b9882021-04-06 12:48:27 -07002266 do_flashall(slot_override, true, wants_wipe, force_flash);
Alex Lightbb9b8a52016-06-29 09:26:44 -07002267 } else {
Andrew Chantd64b9882021-04-06 12:48:27 -07002268 do_flashall(slot_override, skip_secondary, wants_wipe, force_flash);
Alex Lightbb9b8a52016-06-29 09:26:44 -07002269 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002270 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07002271 } else if (command == "update") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002272 bool slot_all = (slot_override == "all");
2273 if (slot_all) {
Daniel Zheng65452d02022-11-30 02:25:31 +00002274 fprintf(stderr,
2275 "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
Daniel Rosenberg92b44762016-07-13 20:03:25 -07002276 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07002277 std::string filename = "update.zip";
2278 if (!args.empty()) {
2279 filename = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002280 }
Andrew Chantd64b9882021-04-06 12:48:27 -07002281 do_update(filename.c_str(), slot_override, skip_secondary || slot_all, force_flash);
Mitchell Wills31dce302016-09-26 10:26:21 -07002282 wants_reboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002283 } else if (command == FB_CMD_SET_ACTIVE) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002284 std::string slot = verify_slot(next_arg(&args), false);
Tom Cherry9027af02018-09-24 15:48:09 -07002285 fb->SetActive(slot);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002286 } else if (command == "stage") {
2287 std::string filename = next_arg(&args);
2288
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002289 struct fastboot_buffer buf;
Aaron Wisnerdb511202018-06-26 15:38:35 -05002290 if (!load_buf(filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002291 die("cannot load '%s'", filename.c_str());
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08002292 }
Yifan Hong58532df2021-03-22 16:39:13 -07002293 fb->Download(filename, buf.fd.get(), buf.sz);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002294 } else if (command == "get_staged") {
2295 std::string filename = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002296 fb->Upload(filename);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002297 } else if (command == FB_CMD_OEM) {
2298 do_oem_command(FB_CMD_OEM, &args);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002299 } else if (command == "flashing") {
2300 if (args.empty()) {
2301 syntax_error("missing 'flashing' command");
Daniel Zheng65452d02022-11-30 02:25:31 +00002302 } else if (args.size() == 1 &&
2303 (args[0] == "unlock" || args[0] == "lock" || args[0] == "unlock_critical" ||
2304 args[0] == "lock_critical" || args[0] == "get_unlock_ability")) {
Elliott Hughes1eec97a2017-05-15 16:53:53 -07002305 do_oem_command("flashing", &args);
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002306 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002307 syntax_error("unknown 'flashing' command %s", args[0].c_str());
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002308 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002309 } else if (command == FB_CMD_CREATE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002310 std::string partition = next_arg(&args);
2311 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002312 fb->CreatePartition(partition, size);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002313 } else if (command == FB_CMD_DELETE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002314 std::string partition = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002315 fb->DeletePartition(partition);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002316 } else if (command == FB_CMD_RESIZE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002317 std::string partition = next_arg(&args);
2318 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002319 fb->ResizePartition(partition, size);
David Anderson1d504e32019-01-15 14:38:20 -08002320 } else if (command == "gsi") {
David Anderson3d782d52019-01-29 13:09:49 -08002321 std::string arg = next_arg(&args);
2322 if (arg == "wipe") {
David Anderson1d504e32019-01-15 14:38:20 -08002323 fb->RawCommand("gsi:wipe", "wiping GSI");
David Anderson3d782d52019-01-29 13:09:49 -08002324 } else if (arg == "disable") {
David Anderson1d504e32019-01-15 14:38:20 -08002325 fb->RawCommand("gsi:disable", "disabling GSI");
2326 } else {
2327 syntax_error("expected 'wipe' or 'disable'");
2328 }
David Anderson7c84b9f2019-06-27 22:15:29 -07002329 } else if (command == "wipe-super") {
2330 std::string image;
2331 if (args.empty()) {
2332 image = find_item_given_name("super_empty.img");
2333 } else {
2334 image = next_arg(&args);
2335 }
2336 do_wipe_super(image, slot_override);
David Andersonab8f4662019-10-21 16:45:59 -07002337 } else if (command == "snapshot-update") {
2338 std::string arg;
2339 if (!args.empty()) {
2340 arg = next_arg(&args);
2341 }
David Anderson220ddb12019-10-31 18:02:41 -07002342 if (!arg.empty() && (arg != "cancel" && arg != "merge")) {
2343 syntax_error("expected: snapshot-update [cancel|merge]");
David Andersonab8f4662019-10-21 16:45:59 -07002344 }
2345 fb->SnapshotUpdateCommand(arg);
Yifan Hongbcd27702021-02-16 19:37:32 -08002346 } else if (command == FB_CMD_FETCH) {
2347 std::string partition = next_arg(&args);
2348 std::string outfile = next_arg(&args);
2349 do_fetch(partition, slot_override, outfile);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002350 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002351 syntax_error("unknown command %s", command.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002352 }
2353 }
2354
2355 if (wants_wipe) {
David Andersonab8f4662019-10-21 16:45:59 -07002356 if (force_flash) {
2357 CancelSnapshotIfNeeded();
2358 }
Daniel Zheng65452d02022-11-30 02:25:31 +00002359 std::vector<std::string> partitions = {"userdata", "cache", "metadata"};
Paul Crowley4d170062018-04-24 17:06:30 -07002360 for (const auto& partition : partitions) {
2361 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07002362 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
2363 continue;
2364 }
Paul Crowley4d170062018-04-24 17:06:30 -07002365 if (partition_type.empty()) continue;
Tom Cherry9027af02018-09-24 15:48:09 -07002366 fb->Erase(partition);
ThiƩbaud Weksteen5d72d6c2022-07-21 14:43:20 +10002367 fb_perform_format(partition, 1, partition_type, "", fs_options);
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002368 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002369 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002370 if (wants_set_active) {
Tom Cherry9027af02018-09-24 15:48:09 -07002371 fb->SetActive(next_active);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002372 }
Mitchell Wills31dce302016-09-26 10:26:21 -07002373 if (wants_reboot && !skip_reboot) {
Tom Cherry9027af02018-09-24 15:48:09 -07002374 fb->Reboot();
2375 fb->WaitForDisconnect();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002376 } else if (wants_reboot_bootloader) {
Tom Cherry9027af02018-09-24 15:48:09 -07002377 fb->RebootTo("bootloader");
2378 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002379 } else if (wants_reboot_recovery) {
Tom Cherry9027af02018-09-24 15:48:09 -07002380 fb->RebootTo("recovery");
2381 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002382 } else if (wants_reboot_fastboot) {
David Anderson11d6d272018-12-07 16:39:07 -08002383 reboot_to_userspace_fastboot();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002384 }
2385
Elliott Hughes5620d222018-03-28 08:20:00 -07002386 fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
David Anderson03de6452018-09-04 14:32:54 -07002387
Tom Cherry9027af02018-09-24 15:48:09 -07002388 auto* old_transport = fb->set_transport(nullptr);
2389 delete old_transport;
2390
Tom Cherry11f12092018-08-29 21:36:28 -07002391 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002392}
Elliott Hughes6ebec932018-04-10 14:22:13 -07002393
Aaron Wisnerdb511202018-06-26 15:38:35 -05002394void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002395 unsigned year, month, day;
2396 if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2397 syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2398 }
2399 if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2400 if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2401 hdr->SetOsPatchLevel(year, month);
2402}
2403
Aaron Wisnerdb511202018-06-26 15:38:35 -05002404void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002405 unsigned major = 0, minor = 0, patch = 0;
2406 std::vector<std::string> versions = android::base::Split(arg, ".");
2407 if (versions.size() < 1 || versions.size() > 3 ||
2408 (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2409 (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2410 (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2411 (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2412 syntax_error("bad OS version: %s", arg);
2413 }
2414 hdr->SetOsVersion(major, minor, patch);
2415}
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002416
2417unsigned FastBootTool::ParseFsOption(const char* arg) {
2418 unsigned fsOptions = 0;
2419
2420 std::vector<std::string> options = android::base::Split(arg, ",");
Daniel Zheng65452d02022-11-30 02:25:31 +00002421 if (options.size() < 1) syntax_error("bad options: %s", arg);
Jaegeuk Kim638d05e2020-11-09 08:54:13 -08002422
2423 for (size_t i = 0; i < options.size(); ++i) {
2424 if (options[i] == "casefold")
2425 fsOptions |= (1 << FS_OPT_CASEFOLD);
2426 else if (options[i] == "projid")
2427 fsOptions |= (1 << FS_OPT_PROJID);
2428 else if (options[i] == "compress")
2429 fsOptions |= (1 << FS_OPT_COMPRESS);
2430 else
2431 syntax_error("unsupported options: %s", options[i].c_str());
2432 }
2433 return fsOptions;
2434}