blob: 5bd37e183a35d988780b27e008fa839f08b54858 [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
Elliott Hughes82ff3152016-08-31 15:07:18 -070054#include <android-base/file.h>
Elliott Hughes749ae2d2016-06-28 14:48:45 -070055#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080056#include <android-base/parseint.h>
David Pursell2ec418a2016-01-20 08:32:08 -080057#include <android-base/parsenetaddress.h>
Elliott Hughes2810d002016-04-25 14:31:18 -070058#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080059#include <android-base/strings.h>
Chris Fries0ea946c2017-04-12 10:25:57 -050060#include <android-base/unique_fd.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070061#include <build/version.h>
David Anderson89569642018-11-16 15:53:35 -080062#include <liblp/liblp.h>
Dan Willemsenab971b52018-08-29 14:58:02 -070063#include <platform_tools_version.h>
Colin Crossf8387882012-05-24 17:18:41 -070064#include <sparse/sparse.h>
Elliott Hughesd30ad8a2015-03-18 23:12:44 -070065#include <ziparchive/zip_archive.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080066
Elliott Hughes253c18d2015-03-18 22:47:09 -070067#include "bootimg_utils.h"
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -070068#include "constants.h"
Elliott Hughes1b708d32015-12-11 19:07:01 -080069#include "diagnose_usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070070#include "fastboot_driver.h"
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -070071#include "fs.h"
David Pursell2ec418a2016-01-20 08:32:08 -080072#include "tcp.h"
David Pursell0b156632015-10-30 11:22:01 -070073#include "transport.h"
David Pursell4601c972016-02-05 15:35:09 -080074#include "udp.h"
David Pursell0b156632015-10-30 11:22:01 -070075#include "usb.h"
Tom Cherry9027af02018-09-24 15:48:09 -070076#include "util.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080077
Tom Cherrydfd85df2018-09-20 14:45:05 -070078using android::base::ReadFully;
Tom Cherry4aa60b32018-09-05 15:11:44 -070079using android::base::Split;
80using android::base::Trim;
Chris Fries0ea946c2017-04-12 10:25:57 -050081using android::base::unique_fd;
David Anderson0c732342018-11-28 17:10:42 -080082using namespace std::string_literals;
Chris Fries0ea946c2017-04-12 10:25:57 -050083
David Pursell2ec418a2016-01-20 08:32:08 -080084static const char* serial = nullptr;
Elliott Hughes577e8b42018-04-05 16:12:47 -070085
Elliott Hughes577e8b42018-04-05 16:12:47 -070086static bool g_long_listing = false;
Chris Fries6a999712017-04-04 09:52:47 -050087// Don't resparse files in too-big chunks.
88// libsparse will support INT_MAX, but this results in large allocations, so
89// let's keep it at 1GB to avoid memory pressure on the host.
90static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
Elliott Hughes542370d2018-04-19 19:49:44 -070091static uint64_t sparse_limit = 0;
Colin Crossf8387882012-05-24 17:18:41 -070092static int64_t target_sparse_limit = -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093
Elliott Hughes577e8b42018-04-05 16:12:47 -070094static unsigned g_base_addr = 0x10000000;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -080095static boot_img_hdr_v2 g_boot_img_hdr = {};
Elliott Hughes577e8b42018-04-05 16:12:47 -070096static std::string g_cmdline;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -080097static std::string g_dtb_path;
JP Abgrall7b8970c2013-03-07 17:06:41 -080098
David Zeuthenb6ea4352017-08-07 14:29:26 -040099static bool g_disable_verity = false;
100static bool g_disable_verification = false;
101
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000102static const std::string convert_fbe_marker_filename("convert_fbe");
103
Tom Cherry9027af02018-09-24 15:48:09 -0700104fastboot::FastBootDriver* fb = nullptr;
105
Rom Lemarchand622810c2013-06-28 09:54:59 -0700106enum fb_buffer_type {
Chris Fries0ea946c2017-04-12 10:25:57 -0500107 FB_BUFFER_FD,
Rom Lemarchand622810c2013-06-28 09:54:59 -0700108 FB_BUFFER_SPARSE,
109};
110
111struct fastboot_buffer {
112 enum fb_buffer_type type;
Elliott Hughesfc797672015-04-07 20:12:50 -0700113 void* data;
114 int64_t sz;
Chris Fries0ea946c2017-04-12 10:25:57 -0500115 int fd;
David Anderson32e376f2018-08-16 13:43:11 -0700116 int64_t image_size;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700117};
118
David Anderson0debda02018-08-28 13:54:03 -0700119enum class ImageType {
120 // Must be flashed for device to boot into the kernel.
121 BootCritical,
122 // Normal partition to be flashed during "flashall".
123 Normal,
124 // Partition that is never flashed during "flashall".
125 Extra
126};
127
David Anderson32e376f2018-08-16 13:43:11 -0700128struct Image {
Elliott Hughes45964a82017-05-03 22:43:23 -0700129 const char* nickname;
130 const char* img_name;
131 const char* sig_name;
132 const char* part_name;
Hridya Valsarajuf1f0a9c2018-08-02 10:46:21 -0700133 bool optional_if_no_image;
David Anderson0debda02018-08-28 13:54:03 -0700134 ImageType type;
Hridya Valsarajuf1f0a9c2018-08-02 10:46:21 -0700135 bool IsSecondary() const { return nickname == nullptr; }
David Anderson32e376f2018-08-16 13:43:11 -0700136};
137
138static Image images[] = {
Dario Frenic7ea1af2018-05-25 16:07:19 +0100139 // clang-format off
David Anderson0debda02018-08-28 13:54:03 -0700140 { "boot", "boot.img", "boot.sig", "boot", false, ImageType::BootCritical },
141 { nullptr, "boot_other.img", "boot.sig", "boot", true, ImageType::Normal },
142 { "cache", "cache.img", "cache.sig", "cache", true, ImageType::Extra },
143 { "dtbo", "dtbo.img", "dtbo.sig", "dtbo", true, ImageType::BootCritical },
144 { "dts", "dt.img", "dt.sig", "dts", true, ImageType::BootCritical },
145 { "odm", "odm.img", "odm.sig", "odm", true, ImageType::Normal },
146 { "product", "product.img", "product.sig", "product", true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700147 { "recovery", "recovery.img", "recovery.sig", "recovery", true, ImageType::BootCritical },
148 { "super", "super.img", "super.sig", "super", true, ImageType::Extra },
149 { "system", "system.img", "system.sig", "system", false, ImageType::Normal },
Justin Yun5d0ac622019-06-26 09:18:03 +0900150 { "system_ext",
151 "system_ext.img", "system_ext.sig",
152 "system_ext",
153 true, ImageType::Normal },
David Anderson0debda02018-08-28 13:54:03 -0700154 { nullptr, "system_other.img", "system.sig", "system", true, ImageType::Normal },
155 { "userdata", "userdata.img", "userdata.sig", "userdata", true, ImageType::Extra },
156 { "vbmeta", "vbmeta.img", "vbmeta.sig", "vbmeta", true, ImageType::BootCritical },
David Anderson166bfef2018-10-15 14:46:59 -0700157 { "vbmeta_system",
158 "vbmeta_system.img",
159 "vbmeta_system.sig",
160 "vbmeta_system",
David Anderson1109c922018-09-17 17:32:54 -0700161 true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700162 { "vendor", "vendor.img", "vendor.sig", "vendor", true, ImageType::Normal },
Steve Muckle36112432019-08-21 11:16:14 -0700163 { "vendor_boot",
164 "vendor_boot.img", "vendor_boot.sig",
165 "vendor_boot",
166 true, ImageType::BootCritical },
David Anderson0debda02018-08-28 13:54:03 -0700167 { nullptr, "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
Dario Frenic7ea1af2018-05-25 16:07:19 +0100168 // clang-format on
Rom Lemarchand622810c2013-06-28 09:54:59 -0700169};
Brian Swetland2a63bb72009-04-28 16:05:07 -0700170
David Andersone0e693c2018-11-27 20:19:26 -0800171static char* get_android_product_out() {
Elliott Hughes45964a82017-05-03 22:43:23 -0700172 char* dir = getenv("ANDROID_PRODUCT_OUT");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700173 if (dir == nullptr || dir[0] == '\0') {
David Andersone0e693c2018-11-27 20:19:26 -0800174 return nullptr;
175 }
176 return dir;
177}
178
179static std::string find_item_given_name(const std::string& img_name) {
180 char* dir = get_android_product_out();
181 if (!dir) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700182 die("ANDROID_PRODUCT_OUT not set");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700183 }
David Anderson0debda02018-08-28 13:54:03 -0700184 return std::string(dir) + "/" + img_name;
Alex Lightbb9b8a52016-06-29 09:26:44 -0700185}
186
Elliott Hughes29d5d7d2017-05-11 15:05:13 -0700187static std::string find_item(const std::string& item) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700188 for (size_t i = 0; i < arraysize(images); ++i) {
Elliott Hughesd6365a72017-05-08 18:04:49 -0700189 if (images[i].nickname && item == images[i].nickname) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700190 return find_item_given_name(images[i].img_name);
191 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192 }
193
Elliott Hughesd6365a72017-05-08 18:04:49 -0700194 fprintf(stderr, "unknown partition '%s'\n", item.c_str());
Elliott Hughes45964a82017-05-03 22:43:23 -0700195 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196}
197
Tom Cherry9027af02018-09-24 15:48:09 -0700198double last_start_time;
199
200static void Status(const std::string& message) {
201 static constexpr char kStatusFormat[] = "%-50s ";
202 fprintf(stderr, kStatusFormat, message.c_str());
203 last_start_time = now();
204}
205
206static void Epilog(int status) {
207 if (status) {
208 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
209 die("Command failed");
210 } else {
211 double split = now();
212 fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
213 }
214}
215
216static void InfoMessage(const std::string& info) {
217 fprintf(stderr, "(bootloader) %s\n", info.c_str());
218}
219
Elliott Hughesfc797672015-04-07 20:12:50 -0700220static int64_t get_file_size(int fd) {
221 struct stat sb;
Tom Cherrydfd85df2018-09-20 14:45:05 -0700222 if (fstat(fd, &sb) == -1) {
223 die("could not get file size");
224 }
225 return sb.st_size;
Colin Crossf8387882012-05-24 17:18:41 -0700226}
227
Tom Cherrydfd85df2018-09-20 14:45:05 -0700228bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
229 out->clear();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800230
Tom Cherrydfd85df2018-09-20 14:45:05 -0700231 unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
232 if (fd == -1) {
233 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700234 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235
Tom Cherrydfd85df2018-09-20 14:45:05 -0700236 out->resize(get_file_size(fd));
237 return ReadFully(fd, out->data(), out->size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700238}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800239
Elliott Hughesfc797672015-04-07 20:12:50 -0700240static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
Elliott Hughese1746fd2015-08-10 15:30:54 -0700241 if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
242 return -1;
243 }
244
Scott Anderson13081c62012-04-06 12:39:30 -0700245 // require matching serial number or device path if requested
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800246 // at the command line with the -s option.
JP Abgralla032ded2012-06-06 11:53:33 -0700247 if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
248 strcmp(local_serial, info->device_path) != 0)) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249 return 0;
250}
251
Elliott Hughesfc797672015-04-07 20:12:50 -0700252static int match_fastboot(usb_ifc_info* info) {
JP Abgrall7b8970c2013-03-07 17:06:41 -0800253 return match_fastboot_with_serial(info, serial);
254}
255
Elliott Hughesfc797672015-04-07 20:12:50 -0700256static int list_devices_callback(usb_ifc_info* info) {
257 if (match_fastboot_with_serial(info, nullptr) == 0) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800258 std::string serial = info->serial_number;
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700259 if (!info->writable) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800260 serial = UsbNoPermissionsShortHelpText();
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700261 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 if (!serial[0]) {
263 serial = "????????????";
264 }
Scott Anderson866b1bd2012-06-04 20:29:11 -0700265 // output compatible with "adb devices"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700266 if (!g_long_listing) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800267 printf("%s\tfastboot", serial.c_str());
Scott Anderson13081c62012-04-06 12:39:30 -0700268 } else {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800269 printf("%-22s fastboot", serial.c_str());
270 if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
Scott Anderson13081c62012-04-06 12:39:30 -0700271 }
Elliott Hughes1b708d32015-12-11 19:07:01 -0800272 putchar('\n');
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800273 }
274
275 return -1;
276}
277
David Pursell2ec418a2016-01-20 08:32:08 -0800278// Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
279// a specific device, otherwise the first USB device found will be used.
280//
Elliott Hughes855cdf82018-04-02 14:24:03 -0700281// If |serial| is non-null but invalid, this exits.
David Pursell2ec418a2016-01-20 08:32:08 -0800282// Otherwise it blocks until the target is available.
283//
284// The returned Transport is a singleton, so multiple calls to this function will return the same
285// object, and the caller should not attempt to delete the returned Transport.
David Pursell0b156632015-10-30 11:22:01 -0700286static Transport* open_device() {
David Pursell2ec418a2016-01-20 08:32:08 -0800287 bool announce = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800288
David Pursell4601c972016-02-05 15:35:09 -0800289 Socket::Protocol protocol = Socket::Protocol::kTcp;
David Pursell2ec418a2016-01-20 08:32:08 -0800290 std::string host;
David Pursell4601c972016-02-05 15:35:09 -0800291 int port = 0;
292 if (serial != nullptr) {
293 const char* net_address = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800294
David Pursell4601c972016-02-05 15:35:09 -0800295 if (android::base::StartsWith(serial, "tcp:")) {
296 protocol = Socket::Protocol::kTcp;
297 port = tcp::kDefaultPort;
298 net_address = serial + strlen("tcp:");
299 } else if (android::base::StartsWith(serial, "udp:")) {
300 protocol = Socket::Protocol::kUdp;
301 port = udp::kDefaultPort;
302 net_address = serial + strlen("udp:");
303 }
304
305 if (net_address != nullptr) {
306 std::string error;
307 if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700308 die("invalid network address '%s': %s\n", net_address, error.c_str());
David Pursell4601c972016-02-05 15:35:09 -0800309 }
David Pursell2ec418a2016-01-20 08:32:08 -0800310 }
311 }
312
David Anderson1d887432018-08-27 16:47:32 -0700313 Transport* transport = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800314 while (true) {
315 if (!host.empty()) {
316 std::string error;
David Pursell4601c972016-02-05 15:35:09 -0800317 if (protocol == Socket::Protocol::kTcp) {
318 transport = tcp::Connect(host, port, &error).release();
319 } else if (protocol == Socket::Protocol::kUdp) {
320 transport = udp::Connect(host, port, &error).release();
321 }
322
David Pursell2ec418a2016-01-20 08:32:08 -0800323 if (transport == nullptr && announce) {
324 fprintf(stderr, "error: %s\n", error.c_str());
325 }
326 } else {
327 transport = usb_open(match_fastboot);
328 }
329
330 if (transport != nullptr) {
331 return transport;
332 }
333
David Pursell0b156632015-10-30 11:22:01 -0700334 if (announce) {
David Pursell2ec418a2016-01-20 08:32:08 -0800335 announce = false;
Elliott Hughesb46964f2015-08-19 17:49:45 -0700336 fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800337 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800338 std::this_thread::sleep_for(std::chrono::milliseconds(1));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 }
340}
341
Elliott Hughesfc797672015-04-07 20:12:50 -0700342static void list_devices() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800343 // We don't actually open a USB device here,
344 // just getting our callback called so we can
345 // list all the connected devices.
346 usb_open(list_devices_callback);
347}
348
Elliott Hughesd6365a72017-05-08 18:04:49 -0700349static void syntax_error(const char* fmt, ...) {
350 fprintf(stderr, "fastboot: usage: ");
351
352 va_list ap;
353 va_start(ap, fmt);
354 vfprintf(stderr, fmt, ap);
355 va_end(ap);
356
357 fprintf(stderr, "\n");
358 exit(1);
359}
360
361static int show_help() {
362 // clang-format off
363 fprintf(stdout,
Elliott Hughes07fc6822018-05-24 16:36:05 -0700364// 1 2 3 4 5 6 7 8
365// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
Elliott Hughesb76188f2018-04-03 13:30:18 -0700366 "usage: fastboot [OPTION...] COMMAND...\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800367 "\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700368 "flashing:\n"
369 " update ZIP Flash all partitions from an update.zip package.\n"
370 " flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
371 " On A/B devices, flashed slot is set as active.\n"
372 " Secondary images may be flashed to inactive slot.\n"
Elliott Hughes07fc6822018-05-24 16:36:05 -0700373 " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
374 " $ANDROID_PRODUCT_OUT if no filename is given.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700375 "\n"
376 "basics:\n"
377 " devices [-l] List devices in bootloader (-l: with device paths).\n"
378 " getvar NAME Display given bootloader variable.\n"
379 " reboot [bootloader] Reboot device.\n"
380 "\n"
381 "locking/unlocking:\n"
382 " flashing lock|unlock Lock/unlock partitions for flashing\n"
383 " flashing lock_critical|unlock_critical\n"
384 " Lock/unlock 'critical' bootloader partitions.\n"
385 " flashing get_unlock_ability\n"
386 " Check whether unlocking is allowed (1) or not(0).\n"
387 "\n"
388 "advanced:\n"
389 " erase PARTITION Erase a flash partition.\n"
390 " format[:FS_TYPE[:SIZE]] PARTITION\n"
391 " Format a flash partition.\n"
392 " set_active SLOT Set the active slot.\n"
393 " oem [COMMAND...] Execute OEM-specific command.\n"
David Anderson1d504e32019-01-15 14:38:20 -0800394 " gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
David Anderson7c84b9f2019-06-27 22:15:29 -0700395 " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
396 " contain an empty set of default dynamic partitions.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700397 "\n"
398 "boot image:\n"
399 " boot KERNEL [RAMDISK [SECOND]]\n"
400 " Download and boot kernel from RAM.\n"
401 " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
402 " Create boot image and flash it.\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800403 " --dtb DTB Specify path to DTB for boot image header version 2.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700404 " --cmdline CMDLINE Override kernel command line.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700405 " --base ADDRESS Set kernel base address (default: 0x10000000).\n"
406 " --kernel-offset Set kernel offset (default: 0x00008000).\n"
407 " --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
408 " --tags-offset Set tags offset (default: 0x00000100).\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800409 " --dtb-offset Set dtb offset (default: 0x01100000).\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700410 " --page-size BYTES Set flash page size (default: 2048).\n"
411 " --header-version VERSION Set boot image header version.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700412 " --os-version MAJOR[.MINOR[.PATCH]]\n"
413 " Set boot image OS version (default: 0.0.0).\n"
414 " --os-patch-level YYYY-MM-DD\n"
415 " Set boot image OS security patch level.\n"
416 // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
Elliott Hughesb76188f2018-04-03 13:30:18 -0700417 "\n"
Elliott Hughes2e9b7792018-04-04 13:36:44 -0700418 // TODO: what device(s) used this? is there any documentation?
Elliott Hughesb76188f2018-04-03 13:30:18 -0700419 //" continue Continue with autoboot.\n"
420 //"\n"
421 "Android Things:\n"
422 " stage IN_FILE Sends given file to stage for the next command.\n"
423 " 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 -0800424 "\n"
425 "options:\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700426 " -w Wipe userdata.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700427 " -s SERIAL Specify a USB device.\n"
428 " -s tcp|udp:HOST[:PORT] Specify a network device.\n"
Elliott Hughes542370d2018-04-19 19:49:44 -0700429 " -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
David Anderson89569642018-11-16 15:53:35 -0800430 " --force Force a flash operation that may be unsafe.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700431 " --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
432 " non-current slot (default: current active slot).\n"
433 " --set-active[=SLOT] Sets the active slot before rebooting.\n"
434 " --skip-secondary Don't flash secondary slots in flashall/update.\n"
435 " --skip-reboot Don't reboot device after flashing.\n"
436 " --disable-verity Sets disable-verity when flashing vbmeta.\n"
437 " --disable-verification Sets disable-verification when flashing vbmeta.\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000438#if !defined(_WIN32)
Elliott Hughesb76188f2018-04-03 13:30:18 -0700439 " --wipe-and-use-fbe Enable file-based encryption, wiping userdata.\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000440#endif
Elliott Hughesb76188f2018-04-03 13:30:18 -0700441 // TODO: remove --unbuffered?
442 " --unbuffered Don't buffer input or output.\n"
443 " --verbose, -v Verbose output.\n"
444 " --version Display version.\n"
445 " --help, -h Show this message.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446 );
Elliott Hughesd6365a72017-05-08 18:04:49 -0700447 // clang-format off
448 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800449}
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000450
Tom Cherrydfd85df2018-09-20 14:45:05 -0700451static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
452 const std::string& second_stage) {
453 std::vector<char> kernel_data;
454 if (!ReadFileToVector(kernel, &kernel_data)) {
455 die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
456 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800457
Elliott Hughesfc797672015-04-07 20:12:50 -0700458 // Is this actually a boot image?
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800459 if (kernel_data.size() < sizeof(boot_img_hdr_v2)) {
Elliott Hughesaaa3b6b2018-01-18 16:08:24 -0800460 die("cannot load '%s': too short", kernel.c_str());
461 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700462 if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
Elliott Hughes577e8b42018-04-05 16:12:47 -0700463 if (!g_cmdline.empty()) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800464 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
Elliott Hughes577e8b42018-04-05 16:12:47 -0700465 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800466
Elliott Hughes4089d342017-10-27 14:21:12 -0700467 if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800468
Tom Cherrydfd85df2018-09-20 14:45:05 -0700469 return kernel_data;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800470 }
471
Tom Cherrydfd85df2018-09-20 14:45:05 -0700472 std::vector<char> ramdisk_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700473 if (!ramdisk.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700474 if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
475 die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
476 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477 }
478
Tom Cherrydfd85df2018-09-20 14:45:05 -0700479 std::vector<char> second_stage_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700480 if (!second_stage.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700481 if (!ReadFileToVector(second_stage, &second_stage_data)) {
482 die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
483 }
Jeremy Compostellaa42adff2014-07-17 17:17:54 +0200484 }
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800485
486 std::vector<char> dtb_data;
487 if (!g_dtb_path.empty()) {
488 if (g_boot_img_hdr.header_version < 2) {
489 die("Argument dtb not supported for boot image header version %d\n",
490 g_boot_img_hdr.header_version);
491 }
492 if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
493 die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
494 }
495 }
496
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497 fprintf(stderr,"creating boot image...\n");
Elliott Hughesd6365a72017-05-08 18:04:49 -0700498
Tom Cherrydfd85df2018-09-20 14:45:05 -0700499 std::vector<char> out;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800500 boot_img_hdr_v2* boot_image_data = mkbootimg(kernel_data, ramdisk_data, second_stage_data,
501 dtb_data, g_base_addr, g_boot_img_hdr, &out);
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800502
Tom Cherrydfd85df2018-09-20 14:45:05 -0700503 if (!g_cmdline.empty()) bootimg_set_cmdline(boot_image_data, g_cmdline);
504 fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700505 return out;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506}
507
Tom Cherrydfd85df2018-09-20 14:45:05 -0700508static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
509 std::vector<char>* out) {
Elliott Hughesd30ad8a2015-03-18 23:12:44 -0700510 ZipEntry zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700511 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700512 fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
513 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514 }
515
Tom Cherrydfd85df2018-09-20 14:45:05 -0700516 out->resize(zip_entry.uncompressed_length);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517
Tom Cherrydfd85df2018-09-20 14:45:05 -0700518 fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
519 out->size() / 1024 / 1024);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800520
Tom Cherrydfd85df2018-09-20 14:45:05 -0700521 int error = ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()),
522 out->size());
523 if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000524
Tom Cherrydfd85df2018-09-20 14:45:05 -0700525 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526}
527
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700528#if defined(_WIN32)
529
530// TODO: move this to somewhere it can be shared.
531
532#include <windows.h>
533
534// Windows' tmpfile(3) requires administrator rights because
535// it creates temporary files in the root directory.
536static FILE* win32_tmpfile() {
537 char temp_path[PATH_MAX];
538 DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
539 if (nchars == 0 || nchars >= sizeof(temp_path)) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700540 die("GetTempPath failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700541 }
542
543 char filename[PATH_MAX];
544 if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700545 die("GetTempFileName failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700546 }
547
548 return fopen(filename, "w+bTD");
549}
550
551#define tmpfile win32_tmpfile
552
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000553static std::string make_temporary_directory() {
Elliott Hughes4089d342017-10-27 14:21:12 -0700554 die("make_temporary_directory not supported under Windows, sorry!");
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000555}
556
Elliott Hughes855cdf82018-04-02 14:24:03 -0700557static int make_temporary_fd(const char* /*what*/) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700558 // TODO: reimplement to avoid leaking a FILE*.
559 return fileno(tmpfile());
560}
561
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000562#else
563
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700564static std::string make_temporary_template() {
565 const char* tmpdir = getenv("TMPDIR");
566 if (tmpdir == nullptr) tmpdir = P_tmpdir;
567 return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
568}
569
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000570static std::string make_temporary_directory() {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700571 std::string result(make_temporary_template());
572 if (mkdtemp(&result[0]) == nullptr) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700573 die("unable to create temporary directory with template %s: %s",
574 result.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000575 }
576 return result;
577}
578
Elliott Hughes855cdf82018-04-02 14:24:03 -0700579static int make_temporary_fd(const char* what) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700580 std::string path_template(make_temporary_template());
581 int fd = mkstemp(&path_template[0]);
582 if (fd == -1) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700583 die("failed to create temporary file for %s with template %s: %s\n",
584 path_template.c_str(), what, strerror(errno));
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700585 }
586 unlink(path_template.c_str());
587 return fd;
588}
589
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700590#endif
591
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000592static std::string create_fbemarker_tmpdir() {
593 std::string dir = make_temporary_directory();
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000594 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
595 int fd = open(marker_file.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0666);
596 if (fd == -1) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700597 die("unable to create FBE marker file %s locally: %s",
598 marker_file.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000599 }
600 close(fd);
601 return dir;
602}
603
604static void delete_fbemarker_tmpdir(const std::string& dir) {
605 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
606 if (unlink(marker_file.c_str()) == -1) {
607 fprintf(stderr, "Unable to delete FBE marker file %s locally: %d, %s\n",
608 marker_file.c_str(), errno, strerror(errno));
609 return;
610 }
611 if (rmdir(dir.c_str()) == -1) {
612 fprintf(stderr, "Unable to delete FBE marker directory %s locally: %d, %s\n",
613 dir.c_str(), errno, strerror(errno));
614 return;
615 }
616}
617
Elliott Hughes45964a82017-05-03 22:43:23 -0700618static int unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700619 unique_fd fd(make_temporary_fd(entry_name));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700620
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700621 ZipEntry zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700622 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700623 fprintf(stderr, "archive does not contain '%s'\n", entry_name);
David Andersoncf444f32018-08-29 14:15:49 -0700624 errno = ENOENT;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000625 return -1;
626 }
627
Elliott Hughes23af1122017-11-10 08:42:17 -0800628 fprintf(stderr, "extracting %s (%" PRIu32 " MB) to disk...", entry_name,
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700629 zip_entry.uncompressed_length / 1024 / 1024);
Elliott Hughes23af1122017-11-10 08:42:17 -0800630 double start = now();
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700631 int error = ExtractEntryToFile(zip, &zip_entry, fd);
632 if (error != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800633 die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700634 }
635
Elliott Hughes4089d342017-10-27 14:21:12 -0700636 if (lseek(fd, 0, SEEK_SET) != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800637 die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
Elliott Hughes4089d342017-10-27 14:21:12 -0700638 }
639
Elliott Hughes23af1122017-11-10 08:42:17 -0800640 fprintf(stderr, " took %.3fs\n", now() - start);
641
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700642 return fd.release();
Rom Lemarchand622810c2013-06-28 09:54:59 -0700643}
644
Tom Cherry4aa60b32018-09-05 15:11:44 -0700645static void CheckRequirement(const std::string& cur_product, const std::string& var,
646 const std::string& product, bool invert,
647 const std::vector<std::string>& options) {
648 Status("Checking '" + var + "'");
Elliott Hughes5620d222018-03-28 08:20:00 -0700649
Tom Cherry4aa60b32018-09-05 15:11:44 -0700650 double start = now();
651
652 if (!product.empty()) {
653 if (product != cur_product) {
654 double split = now();
655 fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
656 cur_product.c_str(), product.c_str(), (split - start));
657 return;
658 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800659 }
Tom Cherry4aa60b32018-09-05 15:11:44 -0700660
661 std::string var_value;
Tom Cherry9027af02018-09-24 15:48:09 -0700662 if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700663 fprintf(stderr, "FAILED\n\n");
Tom Cherry9027af02018-09-24 15:48:09 -0700664 fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(),
665 fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700666 die("requirements not met!");
667 }
668
669 bool match = false;
670 for (const auto& option : options) {
671 if (option == var_value || (option.back() == '*' &&
672 !var_value.compare(0, option.length() - 1, option, 0,
673 option.length() - 1))) {
674 match = true;
675 break;
676 }
677 }
678
679 if (invert) {
680 match = !match;
681 }
682
683 if (match) {
684 double split = now();
685 fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
686 return;
687 }
688
689 fprintf(stderr, "FAILED\n\n");
690 fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
691 fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
692 for (auto it = std::next(options.begin()); it != options.end(); ++it) {
693 fprintf(stderr, " or '%s'", it->c_str());
694 }
695 fprintf(stderr, ".\n\n");
696 die("requirements not met!");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800697}
698
Tom Cherry4aa60b32018-09-05 15:11:44 -0700699bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
700 bool* invert, std::vector<std::string>* options) {
Elliott Hughes5620d222018-03-28 08:20:00 -0700701 // "require product=alpha|beta|gamma"
702 // "require version-bootloader=1234"
703 // "require-for-product:gamma version-bootloader=istanbul|constantinople"
704 // "require partition-exists=vendor"
Tom Cherry4aa60b32018-09-05 15:11:44 -0700705 *product = "";
706 *invert = false;
Elliott Hughes5620d222018-03-28 08:20:00 -0700707
Tom Cherry4aa60b32018-09-05 15:11:44 -0700708 auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
709 auto require_product_regex =
710 std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
711 std::smatch match_results;
712
713 if (std::regex_match(line, match_results, require_reject_regex)) {
714 *invert = Trim(match_results[1]) == "reject";
715 } else if (std::regex_match(line, match_results, require_product_regex)) {
716 *product = match_results[1];
717 } else {
718 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719 }
720
Tom Cherry4aa60b32018-09-05 15:11:44 -0700721 *name = match_results[2];
Elliott Hughes253c18d2015-03-18 22:47:09 -0700722 // Work around an unfortunate name mismatch.
Tom Cherry4aa60b32018-09-05 15:11:44 -0700723 if (*name == "board") {
724 *name = "product";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800725 }
726
Tom Cherry4aa60b32018-09-05 15:11:44 -0700727 auto raw_options = Split(match_results[3], "|");
728 for (const auto& option : raw_options) {
729 auto trimmed_option = Trim(option);
730 options->emplace_back(trimmed_option);
731 }
732
733 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734}
735
Tom Cherry4aa60b32018-09-05 15:11:44 -0700736// "require partition-exists=x" is a special case, added because of the trouble we had when
737// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
738// missing out new partitions. A device with new partitions can use "partition-exists" to
739// override the fields `optional_if_no_image` in the `images` array.
740static void HandlePartitionExists(const std::vector<std::string>& options) {
741 const std::string& partition_name = options[0];
742 std::string has_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700743 if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
Tom Cherry4aa60b32018-09-05 15:11:44 -0700744 (has_slot != "yes" && has_slot != "no")) {
745 die("device doesn't have required partition %s!", partition_name.c_str());
746 }
747 bool known_partition = false;
748 for (size_t i = 0; i < arraysize(images); ++i) {
749 if (images[i].nickname && images[i].nickname == partition_name) {
750 images[i].optional_if_no_image = false;
751 known_partition = true;
752 }
753 }
754 if (!known_partition) {
755 die("device requires partition %s which is not known to this version of fastboot",
756 partition_name.c_str());
757 }
758}
759
760static void CheckRequirements(const std::string& data) {
761 std::string cur_product;
Tom Cherry9027af02018-09-24 15:48:09 -0700762 if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
763 fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700764 }
765
766 auto lines = Split(data, "\n");
767 for (const auto& line : lines) {
768 if (line.empty()) {
769 continue;
770 }
771
772 std::string name;
773 std::string product;
774 bool invert;
775 std::vector<std::string> options;
776
777 if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
778 fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
779 continue;
780 }
781 if (name == "partition-exists") {
782 HandlePartitionExists(options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800783 } else {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700784 CheckRequirement(cur_product, name, product, invert, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785 }
786 }
787}
788
Tom Cherry9027af02018-09-24 15:48:09 -0700789static void DisplayVarOrError(const std::string& label, const std::string& var) {
790 std::string value;
791
792 if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
793 Status("getvar:" + var);
794 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
795 return;
796 }
797 fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
798}
799
800static void DumpInfo() {
801 fprintf(stderr, "--------------------------------------------\n");
802 DisplayVarOrError("Bootloader Version...", "version-bootloader");
803 DisplayVarOrError("Baseband Version.....", "version-baseband");
804 DisplayVarOrError("Serial Number........", "serialno");
805 fprintf(stderr, "--------------------------------------------\n");
806
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800807}
808
Tao Bao41cf35f2018-04-24 10:54:21 -0700809static struct sparse_file** load_sparse_files(int fd, int64_t max_size) {
Mohamad Ayyash80cc1f62015-03-31 12:09:29 -0700810 struct sparse_file* s = sparse_file_import_auto(fd, false, true);
Elliott Hughes4089d342017-10-27 14:21:12 -0700811 if (!s) die("cannot sparse read file");
Colin Crossf8387882012-05-24 17:18:41 -0700812
Tao Bao41cf35f2018-04-24 10:54:21 -0700813 if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
814 die("invalid max size %" PRId64, max_size);
815 }
816
Elliott Hughesfc797672015-04-07 20:12:50 -0700817 int files = sparse_file_resparse(s, max_size, nullptr, 0);
Elliott Hughes4089d342017-10-27 14:21:12 -0700818 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700819
Elliott Hughes253c18d2015-03-18 22:47:09 -0700820 sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
Elliott Hughes4089d342017-10-27 14:21:12 -0700821 if (!out_s) die("Failed to allocate sparse file array");
Colin Crossf8387882012-05-24 17:18:41 -0700822
823 files = sparse_file_resparse(s, max_size, out_s, files);
Elliott Hughes4089d342017-10-27 14:21:12 -0700824 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700825
826 return out_s;
827}
828
Aaron Wisnerdb511202018-06-26 15:38:35 -0500829static int64_t get_target_sparse_limit() {
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700830 std::string max_download_size;
Tom Cherry9027af02018-09-24 15:48:09 -0700831 if (fb->GetVar("max-download-size", &max_download_size) != fastboot::SUCCESS ||
Elliott Hughes855cdf82018-04-02 14:24:03 -0700832 max_download_size.empty()) {
833 verbose("target didn't report max-download-size");
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700834 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700835 }
836
Elliott Hughes77c0e662015-11-02 15:51:12 -0800837 // Some bootloaders (angler, for example) send spurious whitespace too.
838 max_download_size = android::base::Trim(max_download_size);
839
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700840 uint64_t limit;
Elliott Hughesda46b392016-10-11 17:09:00 -0700841 if (!android::base::ParseUint(max_download_size, &limit)) {
Elliott Hughes3ab05862015-11-02 09:01:53 -0800842 fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700843 return 0;
844 }
Elliott Hughes855cdf82018-04-02 14:24:03 -0700845 if (limit > 0) verbose("target reported max download size of %" PRId64 " bytes", limit);
Colin Crossf8387882012-05-24 17:18:41 -0700846 return limit;
847}
848
Aaron Wisnerdb511202018-06-26 15:38:35 -0500849static int64_t get_sparse_limit(int64_t size) {
Elliott Hughes542370d2018-04-19 19:49:44 -0700850 int64_t limit = sparse_limit;
851 if (limit == 0) {
852 // Unlimited, so see what the target device's limit is.
853 // TODO: shouldn't we apply this limit even if you've used -S?
Colin Crossf8387882012-05-24 17:18:41 -0700854 if (target_sparse_limit == -1) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500855 target_sparse_limit = get_target_sparse_limit();
Colin Crossf8387882012-05-24 17:18:41 -0700856 }
857 if (target_sparse_limit > 0) {
858 limit = target_sparse_limit;
859 } else {
Colin Cross0bbfb392012-07-24 18:05:21 -0700860 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700861 }
862 }
863
864 if (size > limit) {
Chris Fries6a999712017-04-04 09:52:47 -0500865 return std::min(limit, RESPARSE_LIMIT);
Colin Crossf8387882012-05-24 17:18:41 -0700866 }
867
868 return 0;
869}
870
Aaron Wisnerdb511202018-06-26 15:38:35 -0500871static bool load_buf_fd(int fd, struct fastboot_buffer* buf) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700872 int64_t sz = get_file_size(fd);
873 if (sz == -1) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700874 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700875 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -0700876
David Anderson32e376f2018-08-16 13:43:11 -0700877 if (sparse_file* s = sparse_file_import_auto(fd, false, false)) {
878 buf->image_size = sparse_file_len(s, false, false);
879 sparse_file_destroy(s);
880 } else {
881 buf->image_size = sz;
882 }
883
Elliott Hughesa56a7292018-10-26 10:34:53 -0700884 lseek(fd, 0, SEEK_SET);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500885 int64_t limit = get_sparse_limit(sz);
Colin Crossf8387882012-05-24 17:18:41 -0700886 if (limit) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700887 sparse_file** s = load_sparse_files(fd, limit);
888 if (s == nullptr) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700889 return false;
Colin Crossf8387882012-05-24 17:18:41 -0700890 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700891 buf->type = FB_BUFFER_SPARSE;
892 buf->data = s;
Colin Crossf8387882012-05-24 17:18:41 -0700893 } else {
Chris Fries0ea946c2017-04-12 10:25:57 -0500894 buf->type = FB_BUFFER_FD;
895 buf->data = nullptr;
896 buf->fd = fd;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000897 buf->sz = sz;
Colin Crossf8387882012-05-24 17:18:41 -0700898 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700899
Elliott Hughes53ec4952016-05-11 12:39:27 -0700900 return true;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700901}
902
Aaron Wisnerdb511202018-06-26 15:38:35 -0500903static bool load_buf(const char* fname, struct fastboot_buffer* buf) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500904 unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
905
Elliott Hughes53ec4952016-05-11 12:39:27 -0700906 if (fd == -1) {
907 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700908 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500909
910 struct stat s;
911 if (fstat(fd, &s)) {
912 return false;
913 }
914 if (!S_ISREG(s.st_mode)) {
915 errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
916 return false;
917 }
918
Aaron Wisnerdb511202018-06-26 15:38:35 -0500919 return load_buf_fd(fd.release(), buf);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700920}
921
David Zeuthenb6ea4352017-08-07 14:29:26 -0400922static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf) {
923 // Buffer needs to be at least the size of the VBMeta struct which
924 // is 256 bytes.
925 if (buf->sz < 256) {
926 return;
927 }
928
Elliott Hughes855cdf82018-04-02 14:24:03 -0700929 int fd = make_temporary_fd("vbmeta rewriting");
David Zeuthenb6ea4352017-08-07 14:29:26 -0400930
931 std::string data;
932 if (!android::base::ReadFdToString(buf->fd, &data)) {
933 die("Failed reading from vbmeta");
934 }
935
936 // There's a 32-bit big endian |flags| field at offset 120 where
937 // bit 0 corresponds to disable-verity and bit 1 corresponds to
938 // disable-verification.
939 //
940 // See external/avb/libavb/avb_vbmeta_image.h for the layout of
941 // the VBMeta struct.
942 if (g_disable_verity) {
943 data[123] |= 0x01;
944 }
945 if (g_disable_verification) {
946 data[123] |= 0x02;
947 }
948
949 if (!android::base::WriteStringToFd(data, fd)) {
950 die("Failed writing to modified vbmeta");
951 }
952 close(buf->fd);
953 buf->fd = fd;
954 lseek(fd, 0, SEEK_SET);
955}
956
Elliott Hughes5620d222018-03-28 08:20:00 -0700957static void flash_buf(const std::string& partition, struct fastboot_buffer *buf)
Rom Lemarchand622810c2013-06-28 09:54:59 -0700958{
Elliott Hughes253c18d2015-03-18 22:47:09 -0700959 sparse_file** s;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700960
David Zeuthenb6ea4352017-08-07 14:29:26 -0400961 // Rewrite vbmeta if that's what we're flashing and modification has been requested.
962 if ((g_disable_verity || g_disable_verification) &&
Elliott Hughes5620d222018-03-28 08:20:00 -0700963 (partition == "vbmeta" || partition == "vbmeta_a" || partition == "vbmeta_b")) {
David Zeuthenb6ea4352017-08-07 14:29:26 -0400964 rewrite_vbmeta_buffer(buf);
965 }
966
Rom Lemarchand622810c2013-06-28 09:54:59 -0700967 switch (buf->type) {
Josh Gao9da9ac52016-01-19 14:50:18 -0800968 case FB_BUFFER_SPARSE: {
969 std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
Elliott Hughes253c18d2015-03-18 22:47:09 -0700970 s = reinterpret_cast<sparse_file**>(buf->data);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700971 while (*s) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700972 int64_t sz = sparse_file_len(*s, true, false);
Josh Gao9da9ac52016-01-19 14:50:18 -0800973 sparse_files.emplace_back(*s, sz);
974 ++s;
975 }
976
977 for (size_t i = 0; i < sparse_files.size(); ++i) {
978 const auto& pair = sparse_files[i];
Tom Cherry9027af02018-09-24 15:48:09 -0700979 fb->FlashPartition(partition, pair.first, pair.second, i + 1, sparse_files.size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700980 }
981 break;
Josh Gao9da9ac52016-01-19 14:50:18 -0800982 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500983 case FB_BUFFER_FD:
Tom Cherry9027af02018-09-24 15:48:09 -0700984 fb->FlashPartition(partition, buf->fd, buf->sz);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700985 break;
986 default:
987 die("unknown buffer type: %d", buf->type);
988 }
989}
990
Aaron Wisnerdb511202018-06-26 15:38:35 -0500991static std::string get_current_slot() {
Daniel Rosenberg80919472016-06-30 19:25:31 -0700992 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700993 if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
Elliott Hughes42b18a52018-04-10 15:32:21 -0700994 return current_slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -0700995}
996
Aaron Wisnerdb511202018-06-26 15:38:35 -0500997static int get_slot_count() {
Daniel Rosenberg80919472016-06-30 19:25:31 -0700998 std::string var;
Elliott Hughes42b18a52018-04-10 15:32:21 -0700999 int count = 0;
Tom Cherry9027af02018-09-24 15:48:09 -07001000 if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
1001 !android::base::ParseInt(var, &count)) {
Elliott Hughes42b18a52018-04-10 15:32:21 -07001002 return 0;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001003 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001004 return count;
1005}
1006
Aaron Wisnerdb511202018-06-26 15:38:35 -05001007static bool supports_AB() {
1008 return get_slot_count() >= 2;
Alex Lightbb9b8a52016-06-29 09:26:44 -07001009}
1010
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001011// Given a current slot, this returns what the 'other' slot is.
Daniel Rosenberg80919472016-06-30 19:25:31 -07001012static std::string get_other_slot(const std::string& current_slot, int count) {
1013 if (count == 0) return "";
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001014
Daniel Rosenberg80919472016-06-30 19:25:31 -07001015 char next = (current_slot[0] - 'a' + 1)%count + 'a';
1016 return std::string(1, next);
1017}
1018
Aaron Wisnerdb511202018-06-26 15:38:35 -05001019static std::string get_other_slot(const std::string& current_slot) {
1020 return get_other_slot(current_slot, get_slot_count());
Daniel Rosenberg80919472016-06-30 19:25:31 -07001021}
1022
Aaron Wisnerdb511202018-06-26 15:38:35 -05001023static std::string get_other_slot(int count) {
1024 return get_other_slot(get_current_slot(), count);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001025}
1026
Aaron Wisnerdb511202018-06-26 15:38:35 -05001027static std::string get_other_slot() {
1028 return get_other_slot(get_current_slot(), get_slot_count());
Alex Lightbb9b8a52016-06-29 09:26:44 -07001029}
1030
Aaron Wisnerdb511202018-06-26 15:38:35 -05001031static std::string verify_slot(const std::string& slot_name, bool allow_all) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001032 std::string slot = slot_name;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001033 if (slot == "all") {
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001034 if (allow_all) {
1035 return "all";
1036 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001037 int count = get_slot_count();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001038 if (count > 0) {
1039 return "a";
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001040 } else {
Elliott Hughes4089d342017-10-27 14:21:12 -07001041 die("No known slots");
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001042 }
1043 }
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001044 }
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001045
Aaron Wisnerdb511202018-06-26 15:38:35 -05001046 int count = get_slot_count();
Elliott Hughes4089d342017-10-27 14:21:12 -07001047 if (count == 0) die("Device does not support slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001048
Daniel Rosenberg80919472016-06-30 19:25:31 -07001049 if (slot == "other") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001050 std::string other = get_other_slot( count);
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001051 if (other == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001052 die("No known slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001053 }
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001054 return other;
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001055 }
1056
Daniel Rosenberg80919472016-06-30 19:25:31 -07001057 if (slot.size() == 1 && (slot[0]-'a' >= 0 && slot[0]-'a' < count)) return slot;
1058
1059 fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
1060 for (int i=0; i<count; i++) {
1061 fprintf(stderr, "%c\n", (char)(i + 'a'));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001062 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001063
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001064 exit(1);
1065}
1066
Aaron Wisnerdb511202018-06-26 15:38:35 -05001067static std::string verify_slot(const std::string& slot) {
1068 return verify_slot(slot, true);
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001069}
1070
Aaron Wisnerdb511202018-06-26 15:38:35 -05001071static void do_for_partition(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001072 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001073 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001074 std::string current_slot;
1075
Tom Cherry9027af02018-09-24 15:48:09 -07001076 if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001077 /* If has-slot is not supported, the answer is no. */
1078 has_slot = "no";
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001079 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001080 if (has_slot == "yes") {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001081 if (slot == "") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001082 current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001083 if (current_slot == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001084 die("Failed to identify current slot");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001085 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001086 func(part + "_" + current_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001087 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001088 func(part + '_' + slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001089 }
1090 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001091 if (force_slot && slot != "") {
David Pursell0b156632015-10-30 11:22:01 -07001092 fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
Daniel Rosenberg80919472016-06-30 19:25:31 -07001093 part.c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001094 }
1095 func(part);
1096 }
1097}
1098
David Pursell0b156632015-10-30 11:22:01 -07001099/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1100 * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1101 * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1102 * partition does not support slots.
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001103 */
Aaron Wisnerdb511202018-06-26 15:38:35 -05001104static void do_for_partitions(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001105 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001106 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001107
Daniel Rosenberg80919472016-06-30 19:25:31 -07001108 if (slot == "all") {
Tom Cherry9027af02018-09-24 15:48:09 -07001109 if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
Elliott Hughes4089d342017-10-27 14:21:12 -07001110 die("Could not check if partition %s has slot %s", part.c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001111 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001112 if (has_slot == "yes") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001113 for (int i=0; i < get_slot_count(); i++) {
1114 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001115 }
1116 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001117 do_for_partition(part, "", func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001118 }
1119 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001120 do_for_partition(part, slot, func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001121 }
1122}
1123
David Anderson629e51c2018-10-25 12:51:25 -07001124static bool is_logical(const std::string& partition) {
1125 std::string value;
1126 return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1127}
1128
David Anderson0c732342018-11-28 17:10:42 -08001129static bool is_retrofit_device() {
1130 std::string value;
1131 if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1132 return false;
1133 }
1134 return android::base::StartsWith(value, "system_");
1135}
1136
Aaron Wisnerdb511202018-06-26 15:38:35 -05001137static void do_flash(const char* pname, const char* fname) {
Rom Lemarchand622810c2013-06-28 09:54:59 -07001138 struct fastboot_buffer buf;
1139
Aaron Wisnerdb511202018-06-26 15:38:35 -05001140 if (!load_buf(fname, &buf)) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001141 die("cannot load '%s': %s", fname, strerror(errno));
Rom Lemarchand622810c2013-06-28 09:54:59 -07001142 }
David Anderson629e51c2018-10-25 12:51:25 -07001143 if (is_logical(pname)) {
1144 fb->ResizePartition(pname, std::to_string(buf.image_size));
1145 }
Rom Lemarchand622810c2013-06-28 09:54:59 -07001146 flash_buf(pname, &buf);
Colin Crossf8387882012-05-24 17:18:41 -07001147}
1148
Daniel Rosenberg13454092016-06-27 19:43:11 -07001149// Sets slot_override as the active slot. If slot_override is blank,
1150// set current slot as active instead. This clears slot-unbootable.
Aaron Wisnerdb511202018-06-26 15:38:35 -05001151static void set_active(const std::string& slot_override) {
1152 if (!supports_AB()) return;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001153
Daniel Rosenberg80919472016-06-30 19:25:31 -07001154 if (slot_override != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001155 fb->SetActive(slot_override);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001156 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001157 std::string current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001158 if (current_slot != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001159 fb->SetActive(current_slot);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001160 }
1161 }
1162}
1163
David Anderson32e376f2018-08-16 13:43:11 -07001164static bool is_userspace_fastboot() {
1165 std::string value;
Tom Cherry9027af02018-09-24 15:48:09 -07001166 return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
David Anderson32e376f2018-08-16 13:43:11 -07001167}
1168
David Anderson1d887432018-08-27 16:47:32 -07001169static void reboot_to_userspace_fastboot() {
Tom Cherry9027af02018-09-24 15:48:09 -07001170 fb->RebootTo("fastboot");
1171
1172 auto* old_transport = fb->set_transport(nullptr);
1173 delete old_transport;
David Anderson1d887432018-08-27 16:47:32 -07001174
1175 // Give the current connection time to close.
1176 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
1177
Tom Cherry9027af02018-09-24 15:48:09 -07001178 fb->set_transport(open_device());
David Anderson11d6d272018-12-07 16:39:07 -08001179
1180 if (!is_userspace_fastboot()) {
1181 die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1182 }
Hridya Valsaraju83d856e2019-05-17 14:24:19 -07001183
1184 // Reset target_sparse_limit after reboot to userspace fastboot. Max
1185 // download sizes may differ in bootloader and fastbootd.
1186 target_sparse_limit = -1;
David Anderson1d887432018-08-27 16:47:32 -07001187}
1188
David Andersoncf444f32018-08-29 14:15:49 -07001189class ImageSource {
1190 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001191 virtual bool ReadFile(const std::string& name, std::vector<char>* out) const = 0;
David Andersoncf444f32018-08-29 14:15:49 -07001192 virtual int OpenFile(const std::string& name) const = 0;
1193};
David Anderson32e376f2018-08-16 13:43:11 -07001194
David Andersoncf444f32018-08-29 14:15:49 -07001195class FlashAllTool {
1196 public:
1197 FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe);
David Anderson32e376f2018-08-16 13:43:11 -07001198
David Andersoncf444f32018-08-29 14:15:49 -07001199 void Flash();
David Anderson32e376f2018-08-16 13:43:11 -07001200
David Andersoncf444f32018-08-29 14:15:49 -07001201 private:
1202 void CheckRequirements();
1203 void DetermineSecondarySlot();
1204 void CollectImages();
1205 void FlashImages(const std::vector<std::pair<const Image*, std::string>>& images);
1206 void FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf);
1207 void UpdateSuperPartition();
David Anderson32e376f2018-08-16 13:43:11 -07001208
David Andersoncf444f32018-08-29 14:15:49 -07001209 const ImageSource& source_;
1210 std::string slot_override_;
1211 bool skip_secondary_;
1212 bool wipe_;
1213 std::string secondary_slot_;
1214 std::vector<std::pair<const Image*, std::string>> boot_images_;
1215 std::vector<std::pair<const Image*, std::string>> os_images_;
1216};
1217
1218FlashAllTool::FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe)
1219 : source_(source),
1220 slot_override_(slot_override),
1221 skip_secondary_(skip_secondary),
1222 wipe_(wipe)
1223{
David Anderson32e376f2018-08-16 13:43:11 -07001224}
1225
David Andersoncf444f32018-08-29 14:15:49 -07001226void FlashAllTool::Flash() {
Tom Cherry9027af02018-09-24 15:48:09 -07001227 DumpInfo();
David Andersoncf444f32018-08-29 14:15:49 -07001228 CheckRequirements();
David Anderson96a9fd42018-11-05 15:21:44 -08001229
1230 // Change the slot first, so we boot into the correct recovery image when
1231 // using fastbootd.
1232 if (slot_override_ == "all") {
1233 set_active("a");
1234 } else {
1235 set_active(slot_override_);
1236 }
1237
David Andersoncf444f32018-08-29 14:15:49 -07001238 DetermineSecondarySlot();
1239 CollectImages();
David Anderson32e376f2018-08-16 13:43:11 -07001240
David Anderson95d40932018-08-28 12:14:33 -07001241 // First flash boot partitions. We allow this to happen either in userspace
1242 // or in bootloader fastboot.
David Andersoncf444f32018-08-29 14:15:49 -07001243 FlashImages(boot_images_);
David Anderson95d40932018-08-28 12:14:33 -07001244
1245 // Sync the super partition. This will reboot to userspace fastboot if needed.
David Andersoncf444f32018-08-29 14:15:49 -07001246 UpdateSuperPartition();
David Anderson95d40932018-08-28 12:14:33 -07001247
1248 // Resize any logical partition to 0, so each partition is reset to 0
1249 // extents, and will achieve more optimal allocation.
David Andersoncf444f32018-08-29 14:15:49 -07001250 for (const auto& [image, slot] : os_images_) {
David Anderson32e376f2018-08-16 13:43:11 -07001251 auto resize_partition = [](const std::string& partition) -> void {
1252 if (is_logical(partition)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001253 fb->ResizePartition(partition, "0");
David Anderson32e376f2018-08-16 13:43:11 -07001254 }
1255 };
David Anderson95d40932018-08-28 12:14:33 -07001256 do_for_partitions(image->part_name, slot, resize_partition, false);
David Anderson32e376f2018-08-16 13:43:11 -07001257 }
1258
David Anderson95d40932018-08-28 12:14:33 -07001259 // Flash OS images, resizing logical partitions as needed.
David Andersoncf444f32018-08-29 14:15:49 -07001260 FlashImages(os_images_);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001261}
1262
David Andersoncf444f32018-08-29 14:15:49 -07001263void FlashAllTool::CheckRequirements() {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001264 std::vector<char> contents;
1265 if (!source_.ReadFile("android-info.txt", &contents)) {
David Andersoncf444f32018-08-29 14:15:49 -07001266 die("could not read android-info.txt");
1267 }
Tom Cherry4aa60b32018-09-05 15:11:44 -07001268 ::CheckRequirements({contents.data(), contents.size()});
David Andersoncf444f32018-08-29 14:15:49 -07001269}
1270
1271void FlashAllTool::DetermineSecondarySlot() {
1272 if (skip_secondary_) {
1273 return;
1274 }
David Anderson96a9fd42018-11-05 15:21:44 -08001275 if (slot_override_ != "" && slot_override_ != "all") {
David Andersoncf444f32018-08-29 14:15:49 -07001276 secondary_slot_ = get_other_slot(slot_override_);
1277 } else {
1278 secondary_slot_ = get_other_slot();
1279 }
1280 if (secondary_slot_ == "") {
1281 if (supports_AB()) {
1282 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1283 }
1284 skip_secondary_ = true;
1285 }
1286}
1287
1288void FlashAllTool::CollectImages() {
1289 for (size_t i = 0; i < arraysize(images); ++i) {
1290 std::string slot = slot_override_;
1291 if (images[i].IsSecondary()) {
1292 if (skip_secondary_) {
1293 continue;
1294 }
1295 slot = secondary_slot_;
1296 }
1297 if (images[i].type == ImageType::BootCritical) {
1298 boot_images_.emplace_back(&images[i], slot);
1299 } else if (images[i].type == ImageType::Normal) {
1300 os_images_.emplace_back(&images[i], slot);
1301 }
1302 }
1303}
1304
1305void FlashAllTool::FlashImages(const std::vector<std::pair<const Image*, std::string>>& images) {
1306 for (const auto& [image, slot] : images) {
1307 fastboot_buffer buf;
1308 int fd = source_.OpenFile(image->img_name);
1309 if (fd < 0 || !load_buf_fd(fd, &buf)) {
1310 if (image->optional_if_no_image) {
1311 continue;
1312 }
1313 die("could not load '%s': %s", image->img_name, strerror(errno));
1314 }
1315 FlashImage(*image, slot, &buf);
1316 }
1317}
1318
1319void FlashAllTool::FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf) {
1320 auto flash = [&, this](const std::string& partition_name) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001321 std::vector<char> signature_data;
1322 if (source_.ReadFile(image.sig_name, &signature_data)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001323 fb->Download("signature", signature_data);
1324 fb->RawCommand("signature", "installing signature");
David Andersoncf444f32018-08-29 14:15:49 -07001325 }
1326
1327 if (is_logical(partition_name)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001328 fb->ResizePartition(partition_name, std::to_string(buf->image_size));
David Andersoncf444f32018-08-29 14:15:49 -07001329 }
1330 flash_buf(partition_name.c_str(), buf);
1331 };
1332 do_for_partitions(image.part_name, slot, flash, false);
1333}
1334
1335void FlashAllTool::UpdateSuperPartition() {
David Andersoncf444f32018-08-29 14:15:49 -07001336 int fd = source_.OpenFile("super_empty.img");
1337 if (fd < 0) {
1338 return;
1339 }
1340 if (!is_userspace_fastboot()) {
1341 reboot_to_userspace_fastboot();
1342 }
David Andersoncf444f32018-08-29 14:15:49 -07001343
David Anderson90fe0a42018-11-05 18:01:32 -08001344 std::string super_name;
1345 if (fb->GetVar("super-partition-name", &super_name) != fastboot::RetCode::SUCCESS) {
1346 super_name = "super";
1347 }
1348 fb->Download(super_name, fd, get_file_size(fd));
1349
1350 std::string command = "update-super:" + super_name;
David Andersoncf444f32018-08-29 14:15:49 -07001351 if (wipe_) {
1352 command += ":wipe";
1353 }
Tom Cherry9027af02018-09-24 15:48:09 -07001354 fb->RawCommand(command, "Updating super partition");
David Anderson0c732342018-11-28 17:10:42 -08001355
1356 // Retrofit devices have two super partitions, named super_a and super_b.
1357 // On these devices, secondary slots must be flashed as physical
1358 // partitions (otherwise they would not mount on first boot). To enforce
1359 // this, we delete any logical partitions for the "other" slot.
1360 if (is_retrofit_device()) {
1361 for (const auto& [image, slot] : os_images_) {
1362 std::string partition_name = image->part_name + "_"s + slot;
1363 if (image->IsSecondary() && is_logical(partition_name)) {
1364 fb->DeletePartition(partition_name);
1365 }
1366 }
1367 }
David Andersoncf444f32018-08-29 14:15:49 -07001368}
1369
1370class ZipImageSource final : public ImageSource {
1371 public:
1372 explicit ZipImageSource(ZipArchiveHandle zip) : zip_(zip) {}
Tom Cherrydfd85df2018-09-20 14:45:05 -07001373 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001374 int OpenFile(const std::string& name) const override;
1375
1376 private:
1377 ZipArchiveHandle zip_;
1378};
1379
Tom Cherrydfd85df2018-09-20 14:45:05 -07001380bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1381 return UnzipToMemory(zip_, name, out);
David Andersoncf444f32018-08-29 14:15:49 -07001382}
1383
1384int ZipImageSource::OpenFile(const std::string& name) const {
1385 return unzip_to_file(zip_, name.c_str());
1386}
1387
1388static void do_update(const char* filename, const std::string& slot_override, bool skip_secondary) {
David Andersoncf444f32018-08-29 14:15:49 -07001389 ZipArchiveHandle zip;
1390 int error = OpenArchive(filename, &zip);
1391 if (error != 0) {
1392 die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1393 }
1394
1395 FlashAllTool tool(ZipImageSource(zip), slot_override, skip_secondary, false);
1396 tool.Flash();
1397
1398 CloseArchive(zip);
1399}
1400
1401class LocalImageSource final : public ImageSource {
1402 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001403 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001404 int OpenFile(const std::string& name) const override;
1405};
1406
Tom Cherrydfd85df2018-09-20 14:45:05 -07001407bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
David Andersoncf444f32018-08-29 14:15:49 -07001408 auto path = find_item_given_name(name);
1409 if (path.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001410 return false;
David Andersoncf444f32018-08-29 14:15:49 -07001411 }
Tom Cherrydfd85df2018-09-20 14:45:05 -07001412 return ReadFileToVector(path, out);
David Andersoncf444f32018-08-29 14:15:49 -07001413}
1414
1415int LocalImageSource::OpenFile(const std::string& name) const {
1416 auto path = find_item_given_name(name);
Hridya Valsaraju1a6f6fe2019-04-03 17:57:00 -07001417 return open(path.c_str(), O_RDONLY | O_BINARY);
David Andersoncf444f32018-08-29 14:15:49 -07001418}
1419
1420static void do_flashall(const std::string& slot_override, bool skip_secondary, bool wipe) {
David Andersoncf444f32018-08-29 14:15:49 -07001421 FlashAllTool tool(LocalImageSource(), slot_override, skip_secondary, wipe);
1422 tool.Flash();
1423}
1424
Elliott Hughesd6365a72017-05-08 18:04:49 -07001425static std::string next_arg(std::vector<std::string>* args) {
1426 if (args->empty()) syntax_error("expected argument");
1427 std::string result = args->front();
1428 args->erase(args->begin());
1429 return result;
Patrick Tjin51e8b032015-09-01 08:15:23 -07001430}
1431
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001432static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001433 if (args->empty()) syntax_error("empty oem command");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001434
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001435 std::string command(cmd);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001436 while (!args->empty()) {
Elliott Hughes29d5d7d2017-05-11 15:05:13 -07001437 command += " " + next_arg(args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001438 }
Tom Cherry9027af02018-09-24 15:48:09 -07001439 fb->RawCommand(command, "");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001440}
1441
Connor O'Brience16a8a2017-02-06 14:39:31 -08001442static std::string fb_fix_numeric_var(std::string var) {
1443 // Some bootloaders (angler, for example), send spurious leading whitespace.
1444 var = android::base::Trim(var);
1445 // Some bootloaders (hammerhead, for example) use implicit hex.
1446 // This code used to use strtol with base 16.
1447 if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
1448 return var;
1449}
1450
Aaron Wisnerdb511202018-06-26 15:38:35 -05001451static unsigned fb_get_flash_block_size(std::string name) {
Connor O'Brience16a8a2017-02-06 14:39:31 -08001452 std::string sizeString;
Tom Cherry9027af02018-09-24 15:48:09 -07001453 if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001454 // This device does not report flash block sizes, so return 0.
Connor O'Brience16a8a2017-02-06 14:39:31 -08001455 return 0;
1456 }
1457 sizeString = fb_fix_numeric_var(sizeString);
1458
1459 unsigned size;
1460 if (!android::base::ParseUint(sizeString, &size)) {
1461 fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1462 return 0;
1463 }
Connor O'Brien6ef5c242017-11-01 17:37:32 -07001464 if ((size & (size - 1)) != 0) {
1465 fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
Connor O'Brience16a8a2017-02-06 14:39:31 -08001466 return 0;
1467 }
1468 return size;
1469}
1470
Aaron Wisnerdb511202018-06-26 15:38:35 -05001471static void fb_perform_format(
Elliott Hughes5620d222018-03-28 08:20:00 -07001472 const std::string& partition, int skip_if_not_supported,
Elliott Hughesd6365a72017-05-08 18:04:49 -07001473 const std::string& type_override, const std::string& size_override,
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001474 const std::string& initial_dir) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001475 std::string partition_type, partition_size;
1476
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001477 struct fastboot_buffer buf;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001478 const char* errMsg = nullptr;
1479 const struct fs_generator* gen = nullptr;
Jin Qian4a335822017-04-18 16:23:18 -07001480 TemporaryFile output;
1481 unique_fd fd;
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001482
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001483 unsigned int limit = INT_MAX;
1484 if (target_sparse_limit > 0 && target_sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001485 limit = target_sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001486 }
1487 if (sparse_limit > 0 && sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001488 limit = sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001489 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001490
Tom Cherry9027af02018-09-24 15:48:09 -07001491 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001492 errMsg = "Can't determine partition type.\n";
1493 goto failed;
1494 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001495 if (!type_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001496 if (partition_type != type_override) {
1497 fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001498 partition.c_str(), partition_type.c_str(), type_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001499 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001500 partition_type = type_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001501 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001502
Tom Cherry9027af02018-09-24 15:48:09 -07001503 if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001504 errMsg = "Unable to get partition size\n";
1505 goto failed;
1506 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001507 if (!size_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001508 if (partition_size != size_override) {
1509 fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001510 partition.c_str(), partition_size.c_str(), size_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001511 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001512 partition_size = size_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001513 }
Connor O'Brience16a8a2017-02-06 14:39:31 -08001514 partition_size = fb_fix_numeric_var(partition_size);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001515
Elliott Hughes8ab9a322015-11-02 14:05:57 -08001516 gen = fs_get_generator(partition_type);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001517 if (!gen) {
1518 if (skip_if_not_supported) {
1519 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001520 fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001521 return;
1522 }
Mark Salyzyna30b6962018-11-20 11:04:15 -08001523 die("Formatting is not supported for file system with type '%s'.",
1524 partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001525 }
1526
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001527 int64_t size;
Elliott Hughesda46b392016-10-11 17:09:00 -07001528 if (!android::base::ParseInt(partition_size, &size)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001529 die("Couldn't parse partition size '%s'.", partition_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001530 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001531
Connor O'Brience16a8a2017-02-06 14:39:31 -08001532 unsigned eraseBlkSize, logicalBlkSize;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001533 eraseBlkSize = fb_get_flash_block_size("erase-block-size");
1534 logicalBlkSize = fb_get_flash_block_size("logical-block-size");
Connor O'Brience16a8a2017-02-06 14:39:31 -08001535
Jin Qian4a335822017-04-18 16:23:18 -07001536 if (fs_generator_generate(gen, output.path, size, initial_dir,
1537 eraseBlkSize, logicalBlkSize)) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001538 die("Cannot generate image for %s", partition.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001539 }
1540
Jin Qian4a335822017-04-18 16:23:18 -07001541 fd.reset(open(output.path, O_RDONLY));
1542 if (fd == -1) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001543 die("Cannot open generated image: %s", strerror(errno));
Jin Qian4a335822017-04-18 16:23:18 -07001544 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001545 if (!load_buf_fd(fd.release(), &buf)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001546 die("Cannot read image: %s", strerror(errno));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001547 }
1548 flash_buf(partition, &buf);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001549 return;
1550
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001551failed:
1552 if (skip_if_not_supported) {
1553 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001554 if (errMsg) fprintf(stderr, "%s", errMsg);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001555 }
Tom Cherry9027af02018-09-24 15:48:09 -07001556 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
Mark Salyzyna30b6962018-11-20 11:04:15 -08001557 if (!skip_if_not_supported) {
1558 die("Command failed");
1559 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001560}
1561
David Anderson89569642018-11-16 15:53:35 -08001562static bool should_flash_in_userspace(const std::string& partition_name) {
David Andersone0e693c2018-11-27 20:19:26 -08001563 if (!get_android_product_out()) {
1564 return false;
1565 }
David Anderson89569642018-11-16 15:53:35 -08001566 auto path = find_item_given_name("super_empty.img");
David Anderson00475802018-12-04 17:05:47 -08001567 if (path.empty() || access(path.c_str(), R_OK)) {
David Anderson89569642018-11-16 15:53:35 -08001568 return false;
1569 }
1570 auto metadata = android::fs_mgr::ReadFromImageFile(path);
1571 if (!metadata) {
1572 return false;
1573 }
1574 for (const auto& partition : metadata->partitions) {
1575 auto candidate = android::fs_mgr::GetPartitionName(partition);
1576 if (partition.attributes & LP_PARTITION_ATTR_SLOT_SUFFIXED) {
1577 // On retrofit devices, we don't know if, or whether, the A or B
1578 // slot has been flashed for dynamic partitions. Instead we add
1579 // both names to the list as a conservative guess.
1580 if (candidate + "_a" == partition_name || candidate + "_b" == partition_name) {
1581 return true;
1582 }
1583 } else if (candidate == partition_name) {
1584 return true;
1585 }
1586 }
1587 return false;
1588}
1589
David Anderson7c84b9f2019-06-27 22:15:29 -07001590static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
1591 std::string* message) {
1592 auto super_device = GetMetadataSuperBlockDevice(metadata);
1593 auto block_size = metadata.geometry.logical_block_size;
1594 auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
1595
1596 if (super_bdev_name != "super") {
1597 // retrofit devices do not allow flashing to the retrofit partitions,
1598 // so enable it if we can.
1599 fb->RawCommand("oem allow-flash-super");
1600 }
1601
1602 // Note: do not use die() in here, since we want TemporaryDir's destructor
1603 // to be called.
1604 TemporaryDir temp_dir;
1605
1606 bool ok;
1607 if (metadata.block_devices.size() > 1) {
1608 ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
1609 } else {
1610 auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
1611 ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
1612 }
1613 if (!ok) {
1614 *message = "Could not generate a flashable super image file";
1615 return false;
1616 }
1617
1618 for (const auto& block_device : metadata.block_devices) {
1619 auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
1620 bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
1621
1622 std::string image_name;
1623 if (metadata.block_devices.size() > 1) {
1624 image_name = "super_" + partition + ".img";
1625 } else {
1626 image_name = partition + ".img";
1627 }
1628
1629 auto image_path = temp_dir.path + "/"s + image_name;
1630 auto flash = [&](const std::string& partition_name) {
1631 do_flash(partition_name.c_str(), image_path.c_str());
1632 };
1633 do_for_partitions(partition, slot, flash, force_slot);
1634
1635 unlink(image_path.c_str());
1636 }
1637 return true;
1638}
1639
1640static void do_wipe_super(const std::string& image, const std::string& slot_override) {
1641 if (access(image.c_str(), R_OK) != 0) {
1642 die("Could not read image: %s", image.c_str());
1643 }
1644 auto metadata = android::fs_mgr::ReadFromImageFile(image);
1645 if (!metadata) {
1646 die("Could not parse image: %s", image.c_str());
1647 }
1648
1649 auto slot = slot_override;
1650 if (slot.empty()) {
1651 slot = get_current_slot();
1652 }
1653
1654 std::string message;
1655 if (!wipe_super(*metadata.get(), slot, &message)) {
1656 die(message);
1657 }
1658}
1659
Aaron Wisnerdb511202018-06-26 15:38:35 -05001660int FastBootTool::Main(int argc, char* argv[]) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001661 bool wants_wipe = false;
1662 bool wants_reboot = false;
1663 bool wants_reboot_bootloader = false;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001664 bool wants_reboot_recovery = false;
1665 bool wants_reboot_fastboot = false;
Mitchell Wills31dce302016-09-26 10:26:21 -07001666 bool skip_reboot = false;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001667 bool wants_set_active = false;
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001668 bool skip_secondary = false;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001669 bool set_fbe_marker = false;
David Anderson89569642018-11-16 15:53:35 -08001670 bool force_flash = false;
Florian Bäuerle27ded482014-11-24 11:29:34 +01001671 int longindex;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001672 std::string slot_override;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001673 std::string next_active;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001674
Elliott Hughes577e8b42018-04-05 16:12:47 -07001675 g_boot_img_hdr.kernel_addr = 0x00008000;
1676 g_boot_img_hdr.ramdisk_addr = 0x01000000;
1677 g_boot_img_hdr.second_addr = 0x00f00000;
1678 g_boot_img_hdr.tags_addr = 0x00000100;
1679 g_boot_img_hdr.page_size = 2048;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001680 g_boot_img_hdr.dtb_addr = 0x01100000;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001681
JP Abgrall7b8970c2013-03-07 17:06:41 -08001682 const struct option longopts[] = {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001683 {"base", required_argument, 0, 0},
1684 {"cmdline", required_argument, 0, 0},
1685 {"disable-verification", no_argument, 0, 0},
1686 {"disable-verity", no_argument, 0, 0},
David Anderson89569642018-11-16 15:53:35 -08001687 {"force", no_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001688 {"header-version", required_argument, 0, 0},
Elliott Hughes379646b2015-06-02 13:50:00 -07001689 {"help", no_argument, 0, 'h'},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001690 {"kernel-offset", required_argument, 0, 0},
1691 {"os-patch-level", required_argument, 0, 0},
1692 {"os-version", required_argument, 0, 0},
1693 {"page-size", required_argument, 0, 0},
1694 {"ramdisk-offset", required_argument, 0, 0},
Daniel Rosenberg7aa38bc2015-11-11 17:29:37 -08001695 {"set-active", optional_argument, 0, 'a'},
Mitchell Wills31dce302016-09-26 10:26:21 -07001696 {"skip-reboot", no_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001697 {"skip-secondary", no_argument, 0, 0},
1698 {"slot", required_argument, 0, 0},
1699 {"tags-offset", required_argument, 0, 0},
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001700 {"dtb", required_argument, 0, 0},
1701 {"dtb-offset", required_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001702 {"unbuffered", no_argument, 0, 0},
Elliott Hughesf238d872018-03-29 14:46:29 -07001703 {"verbose", no_argument, 0, 'v'},
1704 {"version", no_argument, 0, 0},
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001705#if !defined(_WIN32)
1706 {"wipe-and-use-fbe", no_argument, 0, 0},
1707#endif
JP Abgrall7b8970c2013-03-07 17:06:41 -08001708 {0, 0, 0, 0}
1709 };
Colin Cross8879f982012-05-22 17:53:34 -07001710
1711 serial = getenv("ANDROID_SERIAL");
1712
Elliott Hughes577e8b42018-04-05 16:12:47 -07001713 int c;
Elliott Hughesf3192bd2018-04-10 15:38:08 -07001714 while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001715 if (c == 0) {
1716 std::string name{longopts[longindex].name};
1717 if (name == "base") {
1718 g_base_addr = strtoul(optarg, 0, 16);
1719 } else if (name == "cmdline") {
1720 g_cmdline = optarg;
1721 } else if (name == "disable-verification") {
1722 g_disable_verification = true;
1723 } else if (name == "disable-verity") {
1724 g_disable_verity = true;
David Anderson89569642018-11-16 15:53:35 -08001725 } else if (name == "force") {
1726 force_flash = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001727 } else if (name == "header-version") {
1728 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001729 } else if (name == "dtb") {
1730 g_dtb_path = optarg;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001731 } else if (name == "kernel-offset") {
1732 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
1733 } else if (name == "os-patch-level") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001734 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001735 } else if (name == "os-version") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001736 ParseOsVersion(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001737 } else if (name == "page-size") {
1738 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
1739 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
1740 } else if (name == "ramdisk-offset") {
1741 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
1742 } else if (name == "skip-reboot") {
1743 skip_reboot = true;
1744 } else if (name == "skip-secondary") {
1745 skip_secondary = true;
1746 } else if (name == "slot") {
1747 slot_override = optarg;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001748 } else if (name == "dtb-offset") {
1749 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001750 } else if (name == "tags-offset") {
1751 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
1752 } else if (name == "unbuffered") {
Elliott Hughesfc797672015-04-07 20:12:50 -07001753 setvbuf(stdout, nullptr, _IONBF, 0);
1754 setvbuf(stderr, nullptr, _IONBF, 0);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001755 } else if (name == "version") {
Dan Willemsenab971b52018-08-29 14:58:02 -07001756 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION, android::build::GetBuildNumber().c_str());
Elliott Hughes1fd46df2017-03-30 15:08:28 -07001757 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
Elliott Hughes379646b2015-06-02 13:50:00 -07001758 return 0;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001759#if !defined(_WIN32)
Elliott Hughes577e8b42018-04-05 16:12:47 -07001760 } else if (name == "wipe-and-use-fbe") {
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001761 wants_wipe = true;
1762 set_fbe_marker = true;
1763#endif
1764 } else {
Elliott Hughes855cdf82018-04-02 14:24:03 -07001765 die("unknown option %s", longopts[longindex].name);
Florian Bäuerle27ded482014-11-24 11:29:34 +01001766 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07001767 } else {
1768 switch (c) {
1769 case 'a':
1770 wants_set_active = true;
1771 if (optarg) next_active = optarg;
1772 break;
1773 case 'h':
1774 return show_help();
Elliott Hughes577e8b42018-04-05 16:12:47 -07001775 case 'l':
1776 g_long_listing = true;
1777 break;
1778 case 's':
1779 serial = optarg;
1780 break;
1781 case 'S':
Elliott Hughes542370d2018-04-19 19:49:44 -07001782 if (!android::base::ParseByteCount(optarg, &sparse_limit)) {
1783 die("invalid sparse limit %s", optarg);
1784 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07001785 break;
1786 case 'v':
1787 set_verbose();
1788 break;
1789 case 'w':
1790 wants_wipe = true;
1791 break;
1792 case '?':
1793 return 1;
1794 default:
1795 abort();
1796 }
Colin Cross8879f982012-05-22 17:53:34 -07001797 }
1798 }
1799
1800 argc -= optind;
1801 argv += optind;
1802
Elliott Hughesd6365a72017-05-08 18:04:49 -07001803 if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001804
Colin Cross8fb6e062012-07-24 16:36:41 -07001805 if (argc > 0 && !strcmp(*argv, "devices")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001806 list_devices();
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001807 return 0;
1808 }
1809
Colin Crossc7b75dc2012-08-29 18:17:06 -07001810 if (argc > 0 && !strcmp(*argv, "help")) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001811 return show_help();
Colin Crossc7b75dc2012-08-29 18:17:06 -07001812 }
1813
David Pursell0b156632015-10-30 11:22:01 -07001814 Transport* transport = open_device();
David Pursell2ec418a2016-01-20 08:32:08 -08001815 if (transport == nullptr) {
1816 return 1;
1817 }
Tom Cherry9027af02018-09-24 15:48:09 -07001818 fastboot::DriverCallbacks driver_callbacks = {
1819 .prolog = Status,
1820 .epilog = Epilog,
1821 .info = InfoMessage,
1822 };
1823 fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
1824 fb = &fastboot_driver;
David Pursell2ec418a2016-01-20 08:32:08 -08001825
Elliott Hughes5620d222018-03-28 08:20:00 -07001826 const double start = now();
1827
Aaron Wisnerdb511202018-06-26 15:38:35 -05001828 if (slot_override != "") slot_override = verify_slot(slot_override);
1829 if (next_active != "") next_active = verify_slot(next_active, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001830
1831 if (wants_set_active) {
1832 if (next_active == "") {
1833 if (slot_override == "") {
Daniel Rosenberg13454092016-06-27 19:43:11 -07001834 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07001835 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001836 next_active = verify_slot(current_slot, false);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001837 } else {
1838 wants_set_active = false;
1839 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001840 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001841 next_active = verify_slot(slot_override, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001842 }
1843 }
1844 }
Elliott Hughes31dbed72009-10-07 15:38:53 -07001845
Elliott Hughesd6365a72017-05-08 18:04:49 -07001846 std::vector<std::string> args(argv, argv + argc);
1847 while (!args.empty()) {
1848 std::string command = next_arg(&args);
Ken Sumrall5ee5d382012-09-29 14:46:25 -07001849
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001850 if (command == FB_CMD_GETVAR) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001851 std::string variable = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07001852 DisplayVarOrError(variable, variable);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001853 } else if (command == FB_CMD_ERASE) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001854 std::string partition = next_arg(&args);
1855 auto erase = [&](const std::string& partition) {
David Pursell0b156632015-10-30 11:22:01 -07001856 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07001857 if (fb->GetVar("partition-type:" + partition, &partition_type) == fastboot::SUCCESS &&
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001858 fs_get_generator(partition_type) != nullptr) {
1859 fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
1860 partition_type.c_str());
1861 }
Ken Sumrall5ee5d382012-09-29 14:46:25 -07001862
Tom Cherry9027af02018-09-24 15:48:09 -07001863 fb->Erase(partition);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001864 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05001865 do_for_partitions(partition, slot_override, erase, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001866 } else if (android::base::StartsWith(command, "format")) {
1867 // Parsing for: "format[:[type][:[size]]]"
1868 // Some valid things:
1869 // - select only the size, and leave default fs type:
1870 // format::0x4000000 userdata
1871 // - default fs type and size:
1872 // format userdata
1873 // format:: userdata
1874 std::vector<std::string> pieces = android::base::Split(command, ":");
1875 std::string type_override;
1876 if (pieces.size() > 1) type_override = pieces[1].c_str();
1877 std::string size_override;
1878 if (pieces.size() > 2) size_override = pieces[2].c_str();
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001879
Elliott Hughesd6365a72017-05-08 18:04:49 -07001880 std::string partition = next_arg(&args);
1881
1882 auto format = [&](const std::string& partition) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001883 fb_perform_format(partition, 0, type_override, size_override, "");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001884 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07001885 do_for_partitions(partition, slot_override, format, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001886 } else if (command == "signature") {
1887 std::string filename = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07001888 std::vector<char> data;
1889 if (!ReadFileToVector(filename, &data)) {
1890 die("could not load '%s': %s", filename.c_str(), strerror(errno));
1891 }
1892 if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
Tom Cherry9027af02018-09-24 15:48:09 -07001893 fb->Download("signature", data);
1894 fb->RawCommand("signature", "installing signature");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001895 } else if (command == FB_CMD_REBOOT) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001896 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001897
1898 if (args.size() == 1) {
1899 std::string what = next_arg(&args);
1900 if (what == "bootloader") {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001901 wants_reboot = false;
1902 wants_reboot_bootloader = true;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001903 } else if (what == "recovery") {
1904 wants_reboot = false;
1905 wants_reboot_recovery = true;
1906 } else if (what == "fastboot") {
1907 wants_reboot = false;
1908 wants_reboot_fastboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001909 } else {
1910 syntax_error("unknown reboot target %s", what.c_str());
Alexey Polyudove0bfb752017-01-03 19:39:13 -08001911 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001912
Elliott Hughesca85df02015-02-25 10:02:00 -08001913 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001914 if (!args.empty()) syntax_error("junk after reboot command");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001915 } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001916 wants_reboot_bootloader = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001917 } else if (command == FB_CMD_REBOOT_RECOVERY) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001918 wants_reboot_recovery = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001919 } else if (command == FB_CMD_REBOOT_FASTBOOT) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001920 wants_reboot_fastboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001921 } else if (command == FB_CMD_CONTINUE) {
Tom Cherry9027af02018-09-24 15:48:09 -07001922 fb->Continue();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001923 } else if (command == FB_CMD_BOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001924 std::string kernel = next_arg(&args);
1925 std::string ramdisk;
1926 if (!args.empty()) ramdisk = next_arg(&args);
1927 std::string second_stage;
1928 if (!args.empty()) second_stage = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07001929 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
Tom Cherry9027af02018-09-24 15:48:09 -07001930 fb->Download("boot.img", data);
1931 fb->Boot();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001932 } else if (command == FB_CMD_FLASH) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001933 std::string pname = next_arg(&args);
1934
Elliott Hughes2810d002016-04-25 14:31:18 -07001935 std::string fname;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001936 if (!args.empty()) {
1937 fname = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001938 } else {
Elliott Hughes45964a82017-05-03 22:43:23 -07001939 fname = find_item(pname);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001940 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001941 if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001942
1943 auto flash = [&](const std::string &partition) {
David Anderson89569642018-11-16 15:53:35 -08001944 if (should_flash_in_userspace(partition) && !is_userspace_fastboot() &&
1945 !force_flash) {
1946 die("The partition you are trying to flash is dynamic, and "
1947 "should be flashed via fastbootd. Please run:\n"
1948 "\n"
1949 " fastboot reboot fastboot\n"
1950 "\n"
1951 "And try again. If you are intentionally trying to "
1952 "overwrite a fixed partition, use --force.");
1953 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001954 do_flash(partition.c_str(), fname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001955 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07001956 do_for_partitions(pname, slot_override, flash, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001957 } else if (command == "flash:raw") {
1958 std::string partition = next_arg(&args);
1959 std::string kernel = next_arg(&args);
1960 std::string ramdisk;
1961 if (!args.empty()) ramdisk = next_arg(&args);
1962 std::string second_stage;
1963 if (!args.empty()) second_stage = next_arg(&args);
1964
Tom Cherrydfd85df2018-09-20 14:45:05 -07001965 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
1966 auto flashraw = [&data](const std::string& partition) {
Tom Cherry9027af02018-09-24 15:48:09 -07001967 fb->FlashPartition(partition, data);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001968 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05001969 do_for_partitions(partition, slot_override, flashraw, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001970 } else if (command == "flashall") {
Alex Lightbb9b8a52016-06-29 09:26:44 -07001971 if (slot_override == "all") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001972 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
David Anderson32e376f2018-08-16 13:43:11 -07001973 do_flashall(slot_override, true, wants_wipe);
Alex Lightbb9b8a52016-06-29 09:26:44 -07001974 } else {
David Anderson32e376f2018-08-16 13:43:11 -07001975 do_flashall(slot_override, skip_secondary, wants_wipe);
Alex Lightbb9b8a52016-06-29 09:26:44 -07001976 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001977 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001978 } else if (command == "update") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001979 bool slot_all = (slot_override == "all");
1980 if (slot_all) {
1981 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
1982 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001983 std::string filename = "update.zip";
1984 if (!args.empty()) {
1985 filename = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001986 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001987 do_update(filename.c_str(), slot_override, skip_secondary || slot_all);
Mitchell Wills31dce302016-09-26 10:26:21 -07001988 wants_reboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001989 } else if (command == FB_CMD_SET_ACTIVE) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001990 std::string slot = verify_slot(next_arg(&args), false);
Tom Cherry9027af02018-09-24 15:48:09 -07001991 fb->SetActive(slot);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001992 } else if (command == "stage") {
1993 std::string filename = next_arg(&args);
1994
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08001995 struct fastboot_buffer buf;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001996 if (!load_buf(filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001997 die("cannot load '%s'", filename.c_str());
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08001998 }
Tom Cherry9027af02018-09-24 15:48:09 -07001999 fb->Download(filename, buf.fd, buf.sz);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002000 } else if (command == "get_staged") {
2001 std::string filename = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002002 fb->Upload(filename);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002003 } else if (command == FB_CMD_OEM) {
2004 do_oem_command(FB_CMD_OEM, &args);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002005 } else if (command == "flashing") {
2006 if (args.empty()) {
2007 syntax_error("missing 'flashing' command");
2008 } else if (args.size() == 1 && (args[0] == "unlock" || args[0] == "lock" ||
2009 args[0] == "unlock_critical" ||
2010 args[0] == "lock_critical" ||
Elliott Hughes2e9b7792018-04-04 13:36:44 -07002011 args[0] == "get_unlock_ability")) {
Elliott Hughes1eec97a2017-05-15 16:53:53 -07002012 do_oem_command("flashing", &args);
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002013 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002014 syntax_error("unknown 'flashing' command %s", args[0].c_str());
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002015 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002016 } else if (command == FB_CMD_CREATE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002017 std::string partition = next_arg(&args);
2018 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002019 fb->CreatePartition(partition, size);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002020 } else if (command == FB_CMD_DELETE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002021 std::string partition = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002022 fb->DeletePartition(partition);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002023 } else if (command == FB_CMD_RESIZE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002024 std::string partition = next_arg(&args);
2025 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002026 fb->ResizePartition(partition, size);
David Anderson1d504e32019-01-15 14:38:20 -08002027 } else if (command == "gsi") {
David Anderson3d782d52019-01-29 13:09:49 -08002028 std::string arg = next_arg(&args);
2029 if (arg == "wipe") {
David Anderson1d504e32019-01-15 14:38:20 -08002030 fb->RawCommand("gsi:wipe", "wiping GSI");
David Anderson3d782d52019-01-29 13:09:49 -08002031 } else if (arg == "disable") {
David Anderson1d504e32019-01-15 14:38:20 -08002032 fb->RawCommand("gsi:disable", "disabling GSI");
2033 } else {
2034 syntax_error("expected 'wipe' or 'disable'");
2035 }
David Anderson7c84b9f2019-06-27 22:15:29 -07002036 } else if (command == "wipe-super") {
2037 std::string image;
2038 if (args.empty()) {
2039 image = find_item_given_name("super_empty.img");
2040 } else {
2041 image = next_arg(&args);
2042 }
2043 do_wipe_super(image, slot_override);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002044 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002045 syntax_error("unknown command %s", command.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002046 }
2047 }
2048
2049 if (wants_wipe) {
Paul Crowley4d170062018-04-24 17:06:30 -07002050 std::vector<std::string> partitions = { "userdata", "cache", "metadata" };
2051 for (const auto& partition : partitions) {
2052 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07002053 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
2054 continue;
2055 }
Paul Crowley4d170062018-04-24 17:06:30 -07002056 if (partition_type.empty()) continue;
Tom Cherry9027af02018-09-24 15:48:09 -07002057 fb->Erase(partition);
Paul Crowley4d170062018-04-24 17:06:30 -07002058 if (partition == "userdata" && set_fbe_marker) {
2059 fprintf(stderr, "setting FBE marker on initial userdata...\n");
2060 std::string initial_userdata_dir = create_fbemarker_tmpdir();
Aaron Wisnerdb511202018-06-26 15:38:35 -05002061 fb_perform_format(partition, 1, "", "", initial_userdata_dir);
Paul Crowley4d170062018-04-24 17:06:30 -07002062 delete_fbemarker_tmpdir(initial_userdata_dir);
2063 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002064 fb_perform_format(partition, 1, "", "", "");
Paul Crowley4d170062018-04-24 17:06:30 -07002065 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002066 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002067 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002068 if (wants_set_active) {
Tom Cherry9027af02018-09-24 15:48:09 -07002069 fb->SetActive(next_active);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002070 }
Mitchell Wills31dce302016-09-26 10:26:21 -07002071 if (wants_reboot && !skip_reboot) {
Tom Cherry9027af02018-09-24 15:48:09 -07002072 fb->Reboot();
2073 fb->WaitForDisconnect();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002074 } else if (wants_reboot_bootloader) {
Tom Cherry9027af02018-09-24 15:48:09 -07002075 fb->RebootTo("bootloader");
2076 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002077 } else if (wants_reboot_recovery) {
Tom Cherry9027af02018-09-24 15:48:09 -07002078 fb->RebootTo("recovery");
2079 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002080 } else if (wants_reboot_fastboot) {
David Anderson11d6d272018-12-07 16:39:07 -08002081 reboot_to_userspace_fastboot();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002082 }
2083
Elliott Hughes5620d222018-03-28 08:20:00 -07002084 fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
David Anderson03de6452018-09-04 14:32:54 -07002085
Tom Cherry9027af02018-09-24 15:48:09 -07002086 auto* old_transport = fb->set_transport(nullptr);
2087 delete old_transport;
2088
Tom Cherry11f12092018-08-29 21:36:28 -07002089 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002090}
Elliott Hughes6ebec932018-04-10 14:22:13 -07002091
Aaron Wisnerdb511202018-06-26 15:38:35 -05002092void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002093 unsigned year, month, day;
2094 if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2095 syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2096 }
2097 if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2098 if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2099 hdr->SetOsPatchLevel(year, month);
2100}
2101
Aaron Wisnerdb511202018-06-26 15:38:35 -05002102void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002103 unsigned major = 0, minor = 0, patch = 0;
2104 std::vector<std::string> versions = android::base::Split(arg, ".");
2105 if (versions.size() < 1 || versions.size() > 3 ||
2106 (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2107 (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2108 (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2109 (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2110 syntax_error("bad OS version: %s", arg);
2111 }
2112 hdr->SetOsVersion(major, minor, patch);
2113}