blob: 8923f409df965bf6f09231f5e10005f6ce1ed06f [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 },
163 { nullptr, "vendor_other.img", "vendor.sig", "vendor", true, ImageType::Normal },
Dario Frenic7ea1af2018-05-25 16:07:19 +0100164 // clang-format on
Rom Lemarchand622810c2013-06-28 09:54:59 -0700165};
Brian Swetland2a63bb72009-04-28 16:05:07 -0700166
David Andersone0e693c2018-11-27 20:19:26 -0800167static char* get_android_product_out() {
Elliott Hughes45964a82017-05-03 22:43:23 -0700168 char* dir = getenv("ANDROID_PRODUCT_OUT");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700169 if (dir == nullptr || dir[0] == '\0') {
David Andersone0e693c2018-11-27 20:19:26 -0800170 return nullptr;
171 }
172 return dir;
173}
174
175static std::string find_item_given_name(const std::string& img_name) {
176 char* dir = get_android_product_out();
177 if (!dir) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700178 die("ANDROID_PRODUCT_OUT not set");
Alex Lightbb9b8a52016-06-29 09:26:44 -0700179 }
David Anderson0debda02018-08-28 13:54:03 -0700180 return std::string(dir) + "/" + img_name;
Alex Lightbb9b8a52016-06-29 09:26:44 -0700181}
182
Elliott Hughes29d5d7d2017-05-11 15:05:13 -0700183static std::string find_item(const std::string& item) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700184 for (size_t i = 0; i < arraysize(images); ++i) {
Elliott Hughesd6365a72017-05-08 18:04:49 -0700185 if (images[i].nickname && item == images[i].nickname) {
Elliott Hughes45964a82017-05-03 22:43:23 -0700186 return find_item_given_name(images[i].img_name);
187 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188 }
189
Elliott Hughesd6365a72017-05-08 18:04:49 -0700190 fprintf(stderr, "unknown partition '%s'\n", item.c_str());
Elliott Hughes45964a82017-05-03 22:43:23 -0700191 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192}
193
Tom Cherry9027af02018-09-24 15:48:09 -0700194double last_start_time;
195
196static void Status(const std::string& message) {
197 static constexpr char kStatusFormat[] = "%-50s ";
198 fprintf(stderr, kStatusFormat, message.c_str());
199 last_start_time = now();
200}
201
202static void Epilog(int status) {
203 if (status) {
204 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
205 die("Command failed");
206 } else {
207 double split = now();
208 fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
209 }
210}
211
212static void InfoMessage(const std::string& info) {
213 fprintf(stderr, "(bootloader) %s\n", info.c_str());
214}
215
Elliott Hughesfc797672015-04-07 20:12:50 -0700216static int64_t get_file_size(int fd) {
217 struct stat sb;
Tom Cherrydfd85df2018-09-20 14:45:05 -0700218 if (fstat(fd, &sb) == -1) {
219 die("could not get file size");
220 }
221 return sb.st_size;
Colin Crossf8387882012-05-24 17:18:41 -0700222}
223
Tom Cherrydfd85df2018-09-20 14:45:05 -0700224bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
225 out->clear();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800226
Tom Cherrydfd85df2018-09-20 14:45:05 -0700227 unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
228 if (fd == -1) {
229 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700230 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800231
Tom Cherrydfd85df2018-09-20 14:45:05 -0700232 out->resize(get_file_size(fd));
233 return ReadFully(fd, out->data(), out->size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700234}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235
Elliott Hughesfc797672015-04-07 20:12:50 -0700236static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
Elliott Hughese1746fd2015-08-10 15:30:54 -0700237 if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
238 return -1;
239 }
240
Scott Anderson13081c62012-04-06 12:39:30 -0700241 // require matching serial number or device path if requested
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242 // at the command line with the -s option.
JP Abgralla032ded2012-06-06 11:53:33 -0700243 if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
244 strcmp(local_serial, info->device_path) != 0)) return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800245 return 0;
246}
247
Elliott Hughesfc797672015-04-07 20:12:50 -0700248static int match_fastboot(usb_ifc_info* info) {
JP Abgrall7b8970c2013-03-07 17:06:41 -0800249 return match_fastboot_with_serial(info, serial);
250}
251
Elliott Hughesfc797672015-04-07 20:12:50 -0700252static int list_devices_callback(usb_ifc_info* info) {
253 if (match_fastboot_with_serial(info, nullptr) == 0) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800254 std::string serial = info->serial_number;
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700255 if (!info->writable) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800256 serial = UsbNoPermissionsShortHelpText();
Elliott Hughesb4add9b2009-10-06 18:07:49 -0700257 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 if (!serial[0]) {
259 serial = "????????????";
260 }
Scott Anderson866b1bd2012-06-04 20:29:11 -0700261 // output compatible with "adb devices"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700262 if (!g_long_listing) {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800263 printf("%s\tfastboot", serial.c_str());
Scott Anderson13081c62012-04-06 12:39:30 -0700264 } else {
Elliott Hughes1b708d32015-12-11 19:07:01 -0800265 printf("%-22s fastboot", serial.c_str());
266 if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
Scott Anderson13081c62012-04-06 12:39:30 -0700267 }
Elliott Hughes1b708d32015-12-11 19:07:01 -0800268 putchar('\n');
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800269 }
270
271 return -1;
272}
273
David Pursell2ec418a2016-01-20 08:32:08 -0800274// Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
275// a specific device, otherwise the first USB device found will be used.
276//
Elliott Hughes855cdf82018-04-02 14:24:03 -0700277// If |serial| is non-null but invalid, this exits.
David Pursell2ec418a2016-01-20 08:32:08 -0800278// Otherwise it blocks until the target is available.
279//
280// The returned Transport is a singleton, so multiple calls to this function will return the same
281// object, and the caller should not attempt to delete the returned Transport.
David Pursell0b156632015-10-30 11:22:01 -0700282static Transport* open_device() {
David Pursell2ec418a2016-01-20 08:32:08 -0800283 bool announce = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284
David Pursell4601c972016-02-05 15:35:09 -0800285 Socket::Protocol protocol = Socket::Protocol::kTcp;
David Pursell2ec418a2016-01-20 08:32:08 -0800286 std::string host;
David Pursell4601c972016-02-05 15:35:09 -0800287 int port = 0;
288 if (serial != nullptr) {
289 const char* net_address = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800290
David Pursell4601c972016-02-05 15:35:09 -0800291 if (android::base::StartsWith(serial, "tcp:")) {
292 protocol = Socket::Protocol::kTcp;
293 port = tcp::kDefaultPort;
294 net_address = serial + strlen("tcp:");
295 } else if (android::base::StartsWith(serial, "udp:")) {
296 protocol = Socket::Protocol::kUdp;
297 port = udp::kDefaultPort;
298 net_address = serial + strlen("udp:");
299 }
300
301 if (net_address != nullptr) {
302 std::string error;
303 if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700304 die("invalid network address '%s': %s\n", net_address, error.c_str());
David Pursell4601c972016-02-05 15:35:09 -0800305 }
David Pursell2ec418a2016-01-20 08:32:08 -0800306 }
307 }
308
David Anderson1d887432018-08-27 16:47:32 -0700309 Transport* transport = nullptr;
David Pursell2ec418a2016-01-20 08:32:08 -0800310 while (true) {
311 if (!host.empty()) {
312 std::string error;
David Pursell4601c972016-02-05 15:35:09 -0800313 if (protocol == Socket::Protocol::kTcp) {
314 transport = tcp::Connect(host, port, &error).release();
315 } else if (protocol == Socket::Protocol::kUdp) {
316 transport = udp::Connect(host, port, &error).release();
317 }
318
David Pursell2ec418a2016-01-20 08:32:08 -0800319 if (transport == nullptr && announce) {
320 fprintf(stderr, "error: %s\n", error.c_str());
321 }
322 } else {
323 transport = usb_open(match_fastboot);
324 }
325
326 if (transport != nullptr) {
327 return transport;
328 }
329
David Pursell0b156632015-10-30 11:22:01 -0700330 if (announce) {
David Pursell2ec418a2016-01-20 08:32:08 -0800331 announce = false;
Elliott Hughesb46964f2015-08-19 17:49:45 -0700332 fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800334 std::this_thread::sleep_for(std::chrono::milliseconds(1));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800335 }
336}
337
Elliott Hughesfc797672015-04-07 20:12:50 -0700338static void list_devices() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 // We don't actually open a USB device here,
340 // just getting our callback called so we can
341 // list all the connected devices.
342 usb_open(list_devices_callback);
343}
344
Elliott Hughesd6365a72017-05-08 18:04:49 -0700345static void syntax_error(const char* fmt, ...) {
346 fprintf(stderr, "fastboot: usage: ");
347
348 va_list ap;
349 va_start(ap, fmt);
350 vfprintf(stderr, fmt, ap);
351 va_end(ap);
352
353 fprintf(stderr, "\n");
354 exit(1);
355}
356
357static int show_help() {
358 // clang-format off
359 fprintf(stdout,
Elliott Hughes07fc6822018-05-24 16:36:05 -0700360// 1 2 3 4 5 6 7 8
361// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
Elliott Hughesb76188f2018-04-03 13:30:18 -0700362 "usage: fastboot [OPTION...] COMMAND...\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363 "\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700364 "flashing:\n"
365 " update ZIP Flash all partitions from an update.zip package.\n"
366 " flashall Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
367 " On A/B devices, flashed slot is set as active.\n"
368 " Secondary images may be flashed to inactive slot.\n"
Elliott Hughes07fc6822018-05-24 16:36:05 -0700369 " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
370 " $ANDROID_PRODUCT_OUT if no filename is given.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700371 "\n"
372 "basics:\n"
373 " devices [-l] List devices in bootloader (-l: with device paths).\n"
374 " getvar NAME Display given bootloader variable.\n"
375 " reboot [bootloader] Reboot device.\n"
376 "\n"
377 "locking/unlocking:\n"
378 " flashing lock|unlock Lock/unlock partitions for flashing\n"
379 " flashing lock_critical|unlock_critical\n"
380 " Lock/unlock 'critical' bootloader partitions.\n"
381 " flashing get_unlock_ability\n"
382 " Check whether unlocking is allowed (1) or not(0).\n"
383 "\n"
384 "advanced:\n"
385 " erase PARTITION Erase a flash partition.\n"
386 " format[:FS_TYPE[:SIZE]] PARTITION\n"
387 " Format a flash partition.\n"
388 " set_active SLOT Set the active slot.\n"
389 " oem [COMMAND...] Execute OEM-specific command.\n"
David Anderson1d504e32019-01-15 14:38:20 -0800390 " gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
David Anderson7c84b9f2019-06-27 22:15:29 -0700391 " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
392 " contain an empty set of default dynamic partitions.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700393 "\n"
394 "boot image:\n"
395 " boot KERNEL [RAMDISK [SECOND]]\n"
396 " Download and boot kernel from RAM.\n"
397 " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
398 " Create boot image and flash it.\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800399 " --dtb DTB Specify path to DTB for boot image header version 2.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700400 " --cmdline CMDLINE Override kernel command line.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700401 " --base ADDRESS Set kernel base address (default: 0x10000000).\n"
402 " --kernel-offset Set kernel offset (default: 0x00008000).\n"
403 " --ramdisk-offset Set ramdisk offset (default: 0x01000000).\n"
404 " --tags-offset Set tags offset (default: 0x00000100).\n"
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800405 " --dtb-offset Set dtb offset (default: 0x01100000).\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700406 " --page-size BYTES Set flash page size (default: 2048).\n"
407 " --header-version VERSION Set boot image header version.\n"
Elliott Hughes577e8b42018-04-05 16:12:47 -0700408 " --os-version MAJOR[.MINOR[.PATCH]]\n"
409 " Set boot image OS version (default: 0.0.0).\n"
410 " --os-patch-level YYYY-MM-DD\n"
411 " Set boot image OS security patch level.\n"
412 // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
Elliott Hughesb76188f2018-04-03 13:30:18 -0700413 "\n"
Elliott Hughes2e9b7792018-04-04 13:36:44 -0700414 // TODO: what device(s) used this? is there any documentation?
Elliott Hughesb76188f2018-04-03 13:30:18 -0700415 //" continue Continue with autoboot.\n"
416 //"\n"
417 "Android Things:\n"
418 " stage IN_FILE Sends given file to stage for the next command.\n"
419 " 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 -0800420 "\n"
421 "options:\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700422 " -w Wipe userdata.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700423 " -s SERIAL Specify a USB device.\n"
424 " -s tcp|udp:HOST[:PORT] Specify a network device.\n"
Elliott Hughes542370d2018-04-19 19:49:44 -0700425 " -S SIZE[K|M|G] Break into sparse files no larger than SIZE.\n"
David Anderson89569642018-11-16 15:53:35 -0800426 " --force Force a flash operation that may be unsafe.\n"
Elliott Hughesb76188f2018-04-03 13:30:18 -0700427 " --slot SLOT Use SLOT; 'all' for both slots, 'other' for\n"
428 " non-current slot (default: current active slot).\n"
429 " --set-active[=SLOT] Sets the active slot before rebooting.\n"
430 " --skip-secondary Don't flash secondary slots in flashall/update.\n"
431 " --skip-reboot Don't reboot device after flashing.\n"
432 " --disable-verity Sets disable-verity when flashing vbmeta.\n"
433 " --disable-verification Sets disable-verification when flashing vbmeta.\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000434#if !defined(_WIN32)
Elliott Hughesb76188f2018-04-03 13:30:18 -0700435 " --wipe-and-use-fbe Enable file-based encryption, wiping userdata.\n"
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000436#endif
Elliott Hughesb76188f2018-04-03 13:30:18 -0700437 // TODO: remove --unbuffered?
438 " --unbuffered Don't buffer input or output.\n"
439 " --verbose, -v Verbose output.\n"
440 " --version Display version.\n"
441 " --help, -h Show this message.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442 );
Elliott Hughesd6365a72017-05-08 18:04:49 -0700443 // clang-format off
444 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445}
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000446
Tom Cherrydfd85df2018-09-20 14:45:05 -0700447static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
448 const std::string& second_stage) {
449 std::vector<char> kernel_data;
450 if (!ReadFileToVector(kernel, &kernel_data)) {
451 die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
452 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800453
Elliott Hughesfc797672015-04-07 20:12:50 -0700454 // Is this actually a boot image?
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800455 if (kernel_data.size() < sizeof(boot_img_hdr_v2)) {
Elliott Hughesaaa3b6b2018-01-18 16:08:24 -0800456 die("cannot load '%s': too short", kernel.c_str());
457 }
Tom Cherrydfd85df2018-09-20 14:45:05 -0700458 if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
Elliott Hughes577e8b42018-04-05 16:12:47 -0700459 if (!g_cmdline.empty()) {
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800460 bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
Elliott Hughes577e8b42018-04-05 16:12:47 -0700461 }
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800462
Elliott Hughes4089d342017-10-27 14:21:12 -0700463 if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800464
Tom Cherrydfd85df2018-09-20 14:45:05 -0700465 return kernel_data;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466 }
467
Tom Cherrydfd85df2018-09-20 14:45:05 -0700468 std::vector<char> ramdisk_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700469 if (!ramdisk.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700470 if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
471 die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
472 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473 }
474
Tom Cherrydfd85df2018-09-20 14:45:05 -0700475 std::vector<char> second_stage_data;
Elliott Hughesd6365a72017-05-08 18:04:49 -0700476 if (!second_stage.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700477 if (!ReadFileToVector(second_stage, &second_stage_data)) {
478 die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
479 }
Jeremy Compostellaa42adff2014-07-17 17:17:54 +0200480 }
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800481
482 std::vector<char> dtb_data;
483 if (!g_dtb_path.empty()) {
484 if (g_boot_img_hdr.header_version < 2) {
485 die("Argument dtb not supported for boot image header version %d\n",
486 g_boot_img_hdr.header_version);
487 }
488 if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
489 die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
490 }
491 }
492
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493 fprintf(stderr,"creating boot image...\n");
Elliott Hughesd6365a72017-05-08 18:04:49 -0700494
Tom Cherrydfd85df2018-09-20 14:45:05 -0700495 std::vector<char> out;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -0800496 boot_img_hdr_v2* boot_image_data = mkbootimg(kernel_data, ramdisk_data, second_stage_data,
497 dtb_data, g_base_addr, g_boot_img_hdr, &out);
Tsu Chiang Chuangee520552011-02-25 18:38:53 -0800498
Tom Cherrydfd85df2018-09-20 14:45:05 -0700499 if (!g_cmdline.empty()) bootimg_set_cmdline(boot_image_data, g_cmdline);
500 fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
Tom Cherrydfd85df2018-09-20 14:45:05 -0700501 return out;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502}
503
Tom Cherrydfd85df2018-09-20 14:45:05 -0700504static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
505 std::vector<char>* out) {
Elliott Hughesd30ad8a2015-03-18 23:12:44 -0700506 ZipEntry zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700507 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Tom Cherrydfd85df2018-09-20 14:45:05 -0700508 fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
509 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510 }
511
Tom Cherrydfd85df2018-09-20 14:45:05 -0700512 out->resize(zip_entry.uncompressed_length);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800513
Tom Cherrydfd85df2018-09-20 14:45:05 -0700514 fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
515 out->size() / 1024 / 1024);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516
Tom Cherrydfd85df2018-09-20 14:45:05 -0700517 int error = ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()),
518 out->size());
519 if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000520
Tom Cherrydfd85df2018-09-20 14:45:05 -0700521 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522}
523
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700524#if defined(_WIN32)
525
526// TODO: move this to somewhere it can be shared.
527
528#include <windows.h>
529
530// Windows' tmpfile(3) requires administrator rights because
531// it creates temporary files in the root directory.
532static FILE* win32_tmpfile() {
533 char temp_path[PATH_MAX];
534 DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
535 if (nchars == 0 || nchars >= sizeof(temp_path)) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700536 die("GetTempPath failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700537 }
538
539 char filename[PATH_MAX];
540 if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700541 die("GetTempFileName failed, error %ld", GetLastError());
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700542 }
543
544 return fopen(filename, "w+bTD");
545}
546
547#define tmpfile win32_tmpfile
548
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000549static std::string make_temporary_directory() {
Elliott Hughes4089d342017-10-27 14:21:12 -0700550 die("make_temporary_directory not supported under Windows, sorry!");
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000551}
552
Elliott Hughes855cdf82018-04-02 14:24:03 -0700553static int make_temporary_fd(const char* /*what*/) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700554 // TODO: reimplement to avoid leaking a FILE*.
555 return fileno(tmpfile());
556}
557
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000558#else
559
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700560static std::string make_temporary_template() {
561 const char* tmpdir = getenv("TMPDIR");
562 if (tmpdir == nullptr) tmpdir = P_tmpdir;
563 return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
564}
565
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000566static std::string make_temporary_directory() {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700567 std::string result(make_temporary_template());
568 if (mkdtemp(&result[0]) == nullptr) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700569 die("unable to create temporary directory with template %s: %s",
570 result.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000571 }
572 return result;
573}
574
Elliott Hughes855cdf82018-04-02 14:24:03 -0700575static int make_temporary_fd(const char* what) {
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700576 std::string path_template(make_temporary_template());
577 int fd = mkstemp(&path_template[0]);
578 if (fd == -1) {
Elliott Hughesda1dbd62018-05-21 23:02:26 -0700579 die("failed to create temporary file for %s with template %s: %s\n",
580 path_template.c_str(), what, strerror(errno));
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700581 }
582 unlink(path_template.c_str());
583 return fd;
584}
585
Elliott Hughesa26fbee2015-06-03 15:22:11 -0700586#endif
587
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000588static std::string create_fbemarker_tmpdir() {
589 std::string dir = make_temporary_directory();
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000590 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
591 int fd = open(marker_file.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0666);
592 if (fd == -1) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700593 die("unable to create FBE marker file %s locally: %s",
594 marker_file.c_str(), strerror(errno));
Paul Crowley8f7f56e2015-11-27 09:29:37 +0000595 }
596 close(fd);
597 return dir;
598}
599
600static void delete_fbemarker_tmpdir(const std::string& dir) {
601 std::string marker_file = dir + "/" + convert_fbe_marker_filename;
602 if (unlink(marker_file.c_str()) == -1) {
603 fprintf(stderr, "Unable to delete FBE marker file %s locally: %d, %s\n",
604 marker_file.c_str(), errno, strerror(errno));
605 return;
606 }
607 if (rmdir(dir.c_str()) == -1) {
608 fprintf(stderr, "Unable to delete FBE marker directory %s locally: %d, %s\n",
609 dir.c_str(), errno, strerror(errno));
610 return;
611 }
612}
613
Elliott Hughes45964a82017-05-03 22:43:23 -0700614static int unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
Elliott Hughes855cdf82018-04-02 14:24:03 -0700615 unique_fd fd(make_temporary_fd(entry_name));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700616
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700617 ZipEntry zip_entry;
Elliott Hughesb17bf522019-05-03 22:38:44 -0700618 if (FindEntry(zip, entry_name, &zip_entry) != 0) {
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700619 fprintf(stderr, "archive does not contain '%s'\n", entry_name);
David Andersoncf444f32018-08-29 14:15:49 -0700620 errno = ENOENT;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000621 return -1;
622 }
623
Elliott Hughes23af1122017-11-10 08:42:17 -0800624 fprintf(stderr, "extracting %s (%" PRIu32 " MB) to disk...", entry_name,
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700625 zip_entry.uncompressed_length / 1024 / 1024);
Elliott Hughes23af1122017-11-10 08:42:17 -0800626 double start = now();
Elliott Hughesa82c89d2015-03-19 11:44:32 -0700627 int error = ExtractEntryToFile(zip, &zip_entry, fd);
628 if (error != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800629 die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
Rom Lemarchand622810c2013-06-28 09:54:59 -0700630 }
631
Elliott Hughes4089d342017-10-27 14:21:12 -0700632 if (lseek(fd, 0, SEEK_SET) != 0) {
Elliott Hughes23af1122017-11-10 08:42:17 -0800633 die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
Elliott Hughes4089d342017-10-27 14:21:12 -0700634 }
635
Elliott Hughes23af1122017-11-10 08:42:17 -0800636 fprintf(stderr, " took %.3fs\n", now() - start);
637
Elliott Hughesbbfc2812017-04-25 18:33:09 -0700638 return fd.release();
Rom Lemarchand622810c2013-06-28 09:54:59 -0700639}
640
Tom Cherry4aa60b32018-09-05 15:11:44 -0700641static void CheckRequirement(const std::string& cur_product, const std::string& var,
642 const std::string& product, bool invert,
643 const std::vector<std::string>& options) {
644 Status("Checking '" + var + "'");
Elliott Hughes5620d222018-03-28 08:20:00 -0700645
Tom Cherry4aa60b32018-09-05 15:11:44 -0700646 double start = now();
647
648 if (!product.empty()) {
649 if (product != cur_product) {
650 double split = now();
651 fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
652 cur_product.c_str(), product.c_str(), (split - start));
653 return;
654 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655 }
Tom Cherry4aa60b32018-09-05 15:11:44 -0700656
657 std::string var_value;
Tom Cherry9027af02018-09-24 15:48:09 -0700658 if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700659 fprintf(stderr, "FAILED\n\n");
Tom Cherry9027af02018-09-24 15:48:09 -0700660 fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(),
661 fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700662 die("requirements not met!");
663 }
664
665 bool match = false;
666 for (const auto& option : options) {
667 if (option == var_value || (option.back() == '*' &&
668 !var_value.compare(0, option.length() - 1, option, 0,
669 option.length() - 1))) {
670 match = true;
671 break;
672 }
673 }
674
675 if (invert) {
676 match = !match;
677 }
678
679 if (match) {
680 double split = now();
681 fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
682 return;
683 }
684
685 fprintf(stderr, "FAILED\n\n");
686 fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
687 fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
688 for (auto it = std::next(options.begin()); it != options.end(); ++it) {
689 fprintf(stderr, " or '%s'", it->c_str());
690 }
691 fprintf(stderr, ".\n\n");
692 die("requirements not met!");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800693}
694
Tom Cherry4aa60b32018-09-05 15:11:44 -0700695bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
696 bool* invert, std::vector<std::string>* options) {
Elliott Hughes5620d222018-03-28 08:20:00 -0700697 // "require product=alpha|beta|gamma"
698 // "require version-bootloader=1234"
699 // "require-for-product:gamma version-bootloader=istanbul|constantinople"
700 // "require partition-exists=vendor"
Tom Cherry4aa60b32018-09-05 15:11:44 -0700701 *product = "";
702 *invert = false;
Elliott Hughes5620d222018-03-28 08:20:00 -0700703
Tom Cherry4aa60b32018-09-05 15:11:44 -0700704 auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
705 auto require_product_regex =
706 std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
707 std::smatch match_results;
708
709 if (std::regex_match(line, match_results, require_reject_regex)) {
710 *invert = Trim(match_results[1]) == "reject";
711 } else if (std::regex_match(line, match_results, require_product_regex)) {
712 *product = match_results[1];
713 } else {
714 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 }
716
Tom Cherry4aa60b32018-09-05 15:11:44 -0700717 *name = match_results[2];
Elliott Hughes253c18d2015-03-18 22:47:09 -0700718 // Work around an unfortunate name mismatch.
Tom Cherry4aa60b32018-09-05 15:11:44 -0700719 if (*name == "board") {
720 *name = "product";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721 }
722
Tom Cherry4aa60b32018-09-05 15:11:44 -0700723 auto raw_options = Split(match_results[3], "|");
724 for (const auto& option : raw_options) {
725 auto trimmed_option = Trim(option);
726 options->emplace_back(trimmed_option);
727 }
728
729 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730}
731
Tom Cherry4aa60b32018-09-05 15:11:44 -0700732// "require partition-exists=x" is a special case, added because of the trouble we had when
733// Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
734// missing out new partitions. A device with new partitions can use "partition-exists" to
735// override the fields `optional_if_no_image` in the `images` array.
736static void HandlePartitionExists(const std::vector<std::string>& options) {
737 const std::string& partition_name = options[0];
738 std::string has_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700739 if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
Tom Cherry4aa60b32018-09-05 15:11:44 -0700740 (has_slot != "yes" && has_slot != "no")) {
741 die("device doesn't have required partition %s!", partition_name.c_str());
742 }
743 bool known_partition = false;
744 for (size_t i = 0; i < arraysize(images); ++i) {
745 if (images[i].nickname && images[i].nickname == partition_name) {
746 images[i].optional_if_no_image = false;
747 known_partition = true;
748 }
749 }
750 if (!known_partition) {
751 die("device requires partition %s which is not known to this version of fastboot",
752 partition_name.c_str());
753 }
754}
755
756static void CheckRequirements(const std::string& data) {
757 std::string cur_product;
Tom Cherry9027af02018-09-24 15:48:09 -0700758 if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
759 fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
Tom Cherry4aa60b32018-09-05 15:11:44 -0700760 }
761
762 auto lines = Split(data, "\n");
763 for (const auto& line : lines) {
764 if (line.empty()) {
765 continue;
766 }
767
768 std::string name;
769 std::string product;
770 bool invert;
771 std::vector<std::string> options;
772
773 if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
774 fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
775 continue;
776 }
777 if (name == "partition-exists") {
778 HandlePartitionExists(options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800779 } else {
Tom Cherry4aa60b32018-09-05 15:11:44 -0700780 CheckRequirement(cur_product, name, product, invert, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800781 }
782 }
783}
784
Tom Cherry9027af02018-09-24 15:48:09 -0700785static void DisplayVarOrError(const std::string& label, const std::string& var) {
786 std::string value;
787
788 if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
789 Status("getvar:" + var);
790 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
791 return;
792 }
793 fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
794}
795
796static void DumpInfo() {
797 fprintf(stderr, "--------------------------------------------\n");
798 DisplayVarOrError("Bootloader Version...", "version-bootloader");
799 DisplayVarOrError("Baseband Version.....", "version-baseband");
800 DisplayVarOrError("Serial Number........", "serialno");
801 fprintf(stderr, "--------------------------------------------\n");
802
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800803}
804
Tao Bao41cf35f2018-04-24 10:54:21 -0700805static struct sparse_file** load_sparse_files(int fd, int64_t max_size) {
Mohamad Ayyash80cc1f62015-03-31 12:09:29 -0700806 struct sparse_file* s = sparse_file_import_auto(fd, false, true);
Elliott Hughes4089d342017-10-27 14:21:12 -0700807 if (!s) die("cannot sparse read file");
Colin Crossf8387882012-05-24 17:18:41 -0700808
Tao Bao41cf35f2018-04-24 10:54:21 -0700809 if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
810 die("invalid max size %" PRId64, max_size);
811 }
812
Elliott Hughesfc797672015-04-07 20:12:50 -0700813 int files = sparse_file_resparse(s, max_size, nullptr, 0);
Elliott Hughes4089d342017-10-27 14:21:12 -0700814 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700815
Elliott Hughes253c18d2015-03-18 22:47:09 -0700816 sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
Elliott Hughes4089d342017-10-27 14:21:12 -0700817 if (!out_s) die("Failed to allocate sparse file array");
Colin Crossf8387882012-05-24 17:18:41 -0700818
819 files = sparse_file_resparse(s, max_size, out_s, files);
Elliott Hughes4089d342017-10-27 14:21:12 -0700820 if (files < 0) die("Failed to resparse");
Colin Crossf8387882012-05-24 17:18:41 -0700821
822 return out_s;
823}
824
Aaron Wisnerdb511202018-06-26 15:38:35 -0500825static int64_t get_target_sparse_limit() {
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700826 std::string max_download_size;
Tom Cherry9027af02018-09-24 15:48:09 -0700827 if (fb->GetVar("max-download-size", &max_download_size) != fastboot::SUCCESS ||
Elliott Hughes855cdf82018-04-02 14:24:03 -0700828 max_download_size.empty()) {
829 verbose("target didn't report max-download-size");
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700830 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700831 }
832
Elliott Hughes77c0e662015-11-02 15:51:12 -0800833 // Some bootloaders (angler, for example) send spurious whitespace too.
834 max_download_size = android::base::Trim(max_download_size);
835
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700836 uint64_t limit;
Elliott Hughesda46b392016-10-11 17:09:00 -0700837 if (!android::base::ParseUint(max_download_size, &limit)) {
Elliott Hughes3ab05862015-11-02 09:01:53 -0800838 fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -0700839 return 0;
840 }
Elliott Hughes855cdf82018-04-02 14:24:03 -0700841 if (limit > 0) verbose("target reported max download size of %" PRId64 " bytes", limit);
Colin Crossf8387882012-05-24 17:18:41 -0700842 return limit;
843}
844
Aaron Wisnerdb511202018-06-26 15:38:35 -0500845static int64_t get_sparse_limit(int64_t size) {
Elliott Hughes542370d2018-04-19 19:49:44 -0700846 int64_t limit = sparse_limit;
847 if (limit == 0) {
848 // Unlimited, so see what the target device's limit is.
849 // TODO: shouldn't we apply this limit even if you've used -S?
Colin Crossf8387882012-05-24 17:18:41 -0700850 if (target_sparse_limit == -1) {
Aaron Wisnerdb511202018-06-26 15:38:35 -0500851 target_sparse_limit = get_target_sparse_limit();
Colin Crossf8387882012-05-24 17:18:41 -0700852 }
853 if (target_sparse_limit > 0) {
854 limit = target_sparse_limit;
855 } else {
Colin Cross0bbfb392012-07-24 18:05:21 -0700856 return 0;
Colin Crossf8387882012-05-24 17:18:41 -0700857 }
858 }
859
860 if (size > limit) {
Chris Fries6a999712017-04-04 09:52:47 -0500861 return std::min(limit, RESPARSE_LIMIT);
Colin Crossf8387882012-05-24 17:18:41 -0700862 }
863
864 return 0;
865}
866
Aaron Wisnerdb511202018-06-26 15:38:35 -0500867static bool load_buf_fd(int fd, struct fastboot_buffer* buf) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700868 int64_t sz = get_file_size(fd);
869 if (sz == -1) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700870 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700871 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -0700872
David Anderson32e376f2018-08-16 13:43:11 -0700873 if (sparse_file* s = sparse_file_import_auto(fd, false, false)) {
874 buf->image_size = sparse_file_len(s, false, false);
875 sparse_file_destroy(s);
876 } else {
877 buf->image_size = sz;
878 }
879
Elliott Hughesa56a7292018-10-26 10:34:53 -0700880 lseek(fd, 0, SEEK_SET);
Aaron Wisnerdb511202018-06-26 15:38:35 -0500881 int64_t limit = get_sparse_limit(sz);
Colin Crossf8387882012-05-24 17:18:41 -0700882 if (limit) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700883 sparse_file** s = load_sparse_files(fd, limit);
884 if (s == nullptr) {
Elliott Hughes53ec4952016-05-11 12:39:27 -0700885 return false;
Colin Crossf8387882012-05-24 17:18:41 -0700886 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700887 buf->type = FB_BUFFER_SPARSE;
888 buf->data = s;
Colin Crossf8387882012-05-24 17:18:41 -0700889 } else {
Chris Fries0ea946c2017-04-12 10:25:57 -0500890 buf->type = FB_BUFFER_FD;
891 buf->data = nullptr;
892 buf->fd = fd;
Alexander Levitskiy8d7ddb32014-05-07 23:31:59 +0000893 buf->sz = sz;
Colin Crossf8387882012-05-24 17:18:41 -0700894 }
Rom Lemarchand622810c2013-06-28 09:54:59 -0700895
Elliott Hughes53ec4952016-05-11 12:39:27 -0700896 return true;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700897}
898
Aaron Wisnerdb511202018-06-26 15:38:35 -0500899static bool load_buf(const char* fname, struct fastboot_buffer* buf) {
Chris Fries0ea946c2017-04-12 10:25:57 -0500900 unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
901
Elliott Hughes53ec4952016-05-11 12:39:27 -0700902 if (fd == -1) {
903 return false;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700904 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500905
906 struct stat s;
907 if (fstat(fd, &s)) {
908 return false;
909 }
910 if (!S_ISREG(s.st_mode)) {
911 errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
912 return false;
913 }
914
Aaron Wisnerdb511202018-06-26 15:38:35 -0500915 return load_buf_fd(fd.release(), buf);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700916}
917
David Zeuthenb6ea4352017-08-07 14:29:26 -0400918static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf) {
919 // Buffer needs to be at least the size of the VBMeta struct which
920 // is 256 bytes.
921 if (buf->sz < 256) {
922 return;
923 }
924
Elliott Hughes855cdf82018-04-02 14:24:03 -0700925 int fd = make_temporary_fd("vbmeta rewriting");
David Zeuthenb6ea4352017-08-07 14:29:26 -0400926
927 std::string data;
928 if (!android::base::ReadFdToString(buf->fd, &data)) {
929 die("Failed reading from vbmeta");
930 }
931
932 // There's a 32-bit big endian |flags| field at offset 120 where
933 // bit 0 corresponds to disable-verity and bit 1 corresponds to
934 // disable-verification.
935 //
936 // See external/avb/libavb/avb_vbmeta_image.h for the layout of
937 // the VBMeta struct.
938 if (g_disable_verity) {
939 data[123] |= 0x01;
940 }
941 if (g_disable_verification) {
942 data[123] |= 0x02;
943 }
944
945 if (!android::base::WriteStringToFd(data, fd)) {
946 die("Failed writing to modified vbmeta");
947 }
948 close(buf->fd);
949 buf->fd = fd;
950 lseek(fd, 0, SEEK_SET);
951}
952
Elliott Hughes5620d222018-03-28 08:20:00 -0700953static void flash_buf(const std::string& partition, struct fastboot_buffer *buf)
Rom Lemarchand622810c2013-06-28 09:54:59 -0700954{
Elliott Hughes253c18d2015-03-18 22:47:09 -0700955 sparse_file** s;
Rom Lemarchand622810c2013-06-28 09:54:59 -0700956
David Zeuthenb6ea4352017-08-07 14:29:26 -0400957 // Rewrite vbmeta if that's what we're flashing and modification has been requested.
958 if ((g_disable_verity || g_disable_verification) &&
Elliott Hughes5620d222018-03-28 08:20:00 -0700959 (partition == "vbmeta" || partition == "vbmeta_a" || partition == "vbmeta_b")) {
David Zeuthenb6ea4352017-08-07 14:29:26 -0400960 rewrite_vbmeta_buffer(buf);
961 }
962
Rom Lemarchand622810c2013-06-28 09:54:59 -0700963 switch (buf->type) {
Josh Gao9da9ac52016-01-19 14:50:18 -0800964 case FB_BUFFER_SPARSE: {
965 std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
Elliott Hughes253c18d2015-03-18 22:47:09 -0700966 s = reinterpret_cast<sparse_file**>(buf->data);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700967 while (*s) {
Elliott Hughesfc797672015-04-07 20:12:50 -0700968 int64_t sz = sparse_file_len(*s, true, false);
Josh Gao9da9ac52016-01-19 14:50:18 -0800969 sparse_files.emplace_back(*s, sz);
970 ++s;
971 }
972
973 for (size_t i = 0; i < sparse_files.size(); ++i) {
974 const auto& pair = sparse_files[i];
Tom Cherry9027af02018-09-24 15:48:09 -0700975 fb->FlashPartition(partition, pair.first, pair.second, i + 1, sparse_files.size());
Rom Lemarchand622810c2013-06-28 09:54:59 -0700976 }
977 break;
Josh Gao9da9ac52016-01-19 14:50:18 -0800978 }
Chris Fries0ea946c2017-04-12 10:25:57 -0500979 case FB_BUFFER_FD:
Tom Cherry9027af02018-09-24 15:48:09 -0700980 fb->FlashPartition(partition, buf->fd, buf->sz);
Rom Lemarchand622810c2013-06-28 09:54:59 -0700981 break;
982 default:
983 die("unknown buffer type: %d", buf->type);
984 }
985}
986
Aaron Wisnerdb511202018-06-26 15:38:35 -0500987static std::string get_current_slot() {
Daniel Rosenberg80919472016-06-30 19:25:31 -0700988 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -0700989 if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
Elliott Hughes42b18a52018-04-10 15:32:21 -0700990 return current_slot;
Daniel Rosenberg80919472016-06-30 19:25:31 -0700991}
992
Aaron Wisnerdb511202018-06-26 15:38:35 -0500993static int get_slot_count() {
Daniel Rosenberg80919472016-06-30 19:25:31 -0700994 std::string var;
Elliott Hughes42b18a52018-04-10 15:32:21 -0700995 int count = 0;
Tom Cherry9027af02018-09-24 15:48:09 -0700996 if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
997 !android::base::ParseInt(var, &count)) {
Elliott Hughes42b18a52018-04-10 15:32:21 -0700998 return 0;
Daniel Rosenberg80919472016-06-30 19:25:31 -0700999 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001000 return count;
1001}
1002
Aaron Wisnerdb511202018-06-26 15:38:35 -05001003static bool supports_AB() {
1004 return get_slot_count() >= 2;
Alex Lightbb9b8a52016-06-29 09:26:44 -07001005}
1006
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001007// Given a current slot, this returns what the 'other' slot is.
Daniel Rosenberg80919472016-06-30 19:25:31 -07001008static std::string get_other_slot(const std::string& current_slot, int count) {
1009 if (count == 0) return "";
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001010
Daniel Rosenberg80919472016-06-30 19:25:31 -07001011 char next = (current_slot[0] - 'a' + 1)%count + 'a';
1012 return std::string(1, next);
1013}
1014
Aaron Wisnerdb511202018-06-26 15:38:35 -05001015static std::string get_other_slot(const std::string& current_slot) {
1016 return get_other_slot(current_slot, get_slot_count());
Daniel Rosenberg80919472016-06-30 19:25:31 -07001017}
1018
Aaron Wisnerdb511202018-06-26 15:38:35 -05001019static std::string get_other_slot(int count) {
1020 return get_other_slot(get_current_slot(), count);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001021}
1022
Aaron Wisnerdb511202018-06-26 15:38:35 -05001023static std::string get_other_slot() {
1024 return get_other_slot(get_current_slot(), get_slot_count());
Alex Lightbb9b8a52016-06-29 09:26:44 -07001025}
1026
Aaron Wisnerdb511202018-06-26 15:38:35 -05001027static std::string verify_slot(const std::string& slot_name, bool allow_all) {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001028 std::string slot = slot_name;
Daniel Rosenberg80919472016-06-30 19:25:31 -07001029 if (slot == "all") {
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001030 if (allow_all) {
1031 return "all";
1032 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001033 int count = get_slot_count();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001034 if (count > 0) {
1035 return "a";
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001036 } else {
Elliott Hughes4089d342017-10-27 14:21:12 -07001037 die("No known slots");
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001038 }
1039 }
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001040 }
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001041
Aaron Wisnerdb511202018-06-26 15:38:35 -05001042 int count = get_slot_count();
Elliott Hughes4089d342017-10-27 14:21:12 -07001043 if (count == 0) die("Device does not support slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001044
Daniel Rosenberg80919472016-06-30 19:25:31 -07001045 if (slot == "other") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001046 std::string other = get_other_slot( count);
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001047 if (other == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001048 die("No known slots");
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001049 }
Daniel Rosenbergad3d3c12016-06-27 23:03:48 -07001050 return other;
Daniel Rosenbergc1743ba2016-01-05 16:54:40 -08001051 }
1052
Daniel Rosenberg80919472016-06-30 19:25:31 -07001053 if (slot.size() == 1 && (slot[0]-'a' >= 0 && slot[0]-'a' < count)) return slot;
1054
1055 fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
1056 for (int i=0; i<count; i++) {
1057 fprintf(stderr, "%c\n", (char)(i + 'a'));
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001058 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001059
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001060 exit(1);
1061}
1062
Aaron Wisnerdb511202018-06-26 15:38:35 -05001063static std::string verify_slot(const std::string& slot) {
1064 return verify_slot(slot, true);
Daniel Rosenberg9b432052015-11-25 15:17:10 -08001065}
1066
Aaron Wisnerdb511202018-06-26 15:38:35 -05001067static void do_for_partition(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001068 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001069 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001070 std::string current_slot;
1071
Tom Cherry9027af02018-09-24 15:48:09 -07001072 if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001073 /* If has-slot is not supported, the answer is no. */
1074 has_slot = "no";
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001075 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001076 if (has_slot == "yes") {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001077 if (slot == "") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001078 current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001079 if (current_slot == "") {
Elliott Hughes4089d342017-10-27 14:21:12 -07001080 die("Failed to identify current slot");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001081 }
Daniel Rosenberg80919472016-06-30 19:25:31 -07001082 func(part + "_" + current_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001083 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001084 func(part + '_' + slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001085 }
1086 } else {
Daniel Rosenberg80919472016-06-30 19:25:31 -07001087 if (force_slot && slot != "") {
David Pursell0b156632015-10-30 11:22:01 -07001088 fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
Daniel Rosenberg80919472016-06-30 19:25:31 -07001089 part.c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001090 }
1091 func(part);
1092 }
1093}
1094
David Pursell0b156632015-10-30 11:22:01 -07001095/* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1096 * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1097 * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1098 * partition does not support slots.
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001099 */
Aaron Wisnerdb511202018-06-26 15:38:35 -05001100static void do_for_partitions(const std::string& part, const std::string& slot,
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001101 const std::function<void(const std::string&)>& func, bool force_slot) {
Daniel Rosenberga7974792015-11-11 16:13:13 -08001102 std::string has_slot;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001103
Daniel Rosenberg80919472016-06-30 19:25:31 -07001104 if (slot == "all") {
Tom Cherry9027af02018-09-24 15:48:09 -07001105 if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
Elliott Hughes4089d342017-10-27 14:21:12 -07001106 die("Could not check if partition %s has slot %s", part.c_str(), slot.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001107 }
Daniel Rosenberga7974792015-11-11 16:13:13 -08001108 if (has_slot == "yes") {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001109 for (int i=0; i < get_slot_count(); i++) {
1110 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001111 }
1112 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001113 do_for_partition(part, "", func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001114 }
1115 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001116 do_for_partition(part, slot, func, force_slot);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001117 }
1118}
1119
David Anderson629e51c2018-10-25 12:51:25 -07001120static bool is_logical(const std::string& partition) {
1121 std::string value;
1122 return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1123}
1124
David Anderson0c732342018-11-28 17:10:42 -08001125static bool is_retrofit_device() {
1126 std::string value;
1127 if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1128 return false;
1129 }
1130 return android::base::StartsWith(value, "system_");
1131}
1132
Aaron Wisnerdb511202018-06-26 15:38:35 -05001133static void do_flash(const char* pname, const char* fname) {
Rom Lemarchand622810c2013-06-28 09:54:59 -07001134 struct fastboot_buffer buf;
1135
Aaron Wisnerdb511202018-06-26 15:38:35 -05001136 if (!load_buf(fname, &buf)) {
Elliott Hughes53ec4952016-05-11 12:39:27 -07001137 die("cannot load '%s': %s", fname, strerror(errno));
Rom Lemarchand622810c2013-06-28 09:54:59 -07001138 }
David Anderson629e51c2018-10-25 12:51:25 -07001139 if (is_logical(pname)) {
1140 fb->ResizePartition(pname, std::to_string(buf.image_size));
1141 }
Rom Lemarchand622810c2013-06-28 09:54:59 -07001142 flash_buf(pname, &buf);
Colin Crossf8387882012-05-24 17:18:41 -07001143}
1144
Daniel Rosenberg13454092016-06-27 19:43:11 -07001145// Sets slot_override as the active slot. If slot_override is blank,
1146// set current slot as active instead. This clears slot-unbootable.
Aaron Wisnerdb511202018-06-26 15:38:35 -05001147static void set_active(const std::string& slot_override) {
1148 if (!supports_AB()) return;
Elliott Hughes42b18a52018-04-10 15:32:21 -07001149
Daniel Rosenberg80919472016-06-30 19:25:31 -07001150 if (slot_override != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001151 fb->SetActive(slot_override);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001152 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001153 std::string current_slot = get_current_slot();
Daniel Rosenberg80919472016-06-30 19:25:31 -07001154 if (current_slot != "") {
Tom Cherry9027af02018-09-24 15:48:09 -07001155 fb->SetActive(current_slot);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001156 }
1157 }
1158}
1159
David Anderson32e376f2018-08-16 13:43:11 -07001160static bool is_userspace_fastboot() {
1161 std::string value;
Tom Cherry9027af02018-09-24 15:48:09 -07001162 return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
David Anderson32e376f2018-08-16 13:43:11 -07001163}
1164
David Anderson1d887432018-08-27 16:47:32 -07001165static void reboot_to_userspace_fastboot() {
Tom Cherry9027af02018-09-24 15:48:09 -07001166 fb->RebootTo("fastboot");
1167
1168 auto* old_transport = fb->set_transport(nullptr);
1169 delete old_transport;
David Anderson1d887432018-08-27 16:47:32 -07001170
1171 // Give the current connection time to close.
1172 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
1173
Tom Cherry9027af02018-09-24 15:48:09 -07001174 fb->set_transport(open_device());
David Anderson11d6d272018-12-07 16:39:07 -08001175
1176 if (!is_userspace_fastboot()) {
1177 die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1178 }
Hridya Valsaraju83d856e2019-05-17 14:24:19 -07001179
1180 // Reset target_sparse_limit after reboot to userspace fastboot. Max
1181 // download sizes may differ in bootloader and fastbootd.
1182 target_sparse_limit = -1;
David Anderson1d887432018-08-27 16:47:32 -07001183}
1184
David Andersoncf444f32018-08-29 14:15:49 -07001185class ImageSource {
1186 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001187 virtual bool ReadFile(const std::string& name, std::vector<char>* out) const = 0;
David Andersoncf444f32018-08-29 14:15:49 -07001188 virtual int OpenFile(const std::string& name) const = 0;
1189};
David Anderson32e376f2018-08-16 13:43:11 -07001190
David Andersoncf444f32018-08-29 14:15:49 -07001191class FlashAllTool {
1192 public:
1193 FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe);
David Anderson32e376f2018-08-16 13:43:11 -07001194
David Andersoncf444f32018-08-29 14:15:49 -07001195 void Flash();
David Anderson32e376f2018-08-16 13:43:11 -07001196
David Andersoncf444f32018-08-29 14:15:49 -07001197 private:
1198 void CheckRequirements();
1199 void DetermineSecondarySlot();
1200 void CollectImages();
1201 void FlashImages(const std::vector<std::pair<const Image*, std::string>>& images);
1202 void FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf);
1203 void UpdateSuperPartition();
David Anderson32e376f2018-08-16 13:43:11 -07001204
David Andersoncf444f32018-08-29 14:15:49 -07001205 const ImageSource& source_;
1206 std::string slot_override_;
1207 bool skip_secondary_;
1208 bool wipe_;
1209 std::string secondary_slot_;
1210 std::vector<std::pair<const Image*, std::string>> boot_images_;
1211 std::vector<std::pair<const Image*, std::string>> os_images_;
1212};
1213
1214FlashAllTool::FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe)
1215 : source_(source),
1216 slot_override_(slot_override),
1217 skip_secondary_(skip_secondary),
1218 wipe_(wipe)
1219{
David Anderson32e376f2018-08-16 13:43:11 -07001220}
1221
David Andersoncf444f32018-08-29 14:15:49 -07001222void FlashAllTool::Flash() {
Tom Cherry9027af02018-09-24 15:48:09 -07001223 DumpInfo();
David Andersoncf444f32018-08-29 14:15:49 -07001224 CheckRequirements();
David Anderson96a9fd42018-11-05 15:21:44 -08001225
1226 // Change the slot first, so we boot into the correct recovery image when
1227 // using fastbootd.
1228 if (slot_override_ == "all") {
1229 set_active("a");
1230 } else {
1231 set_active(slot_override_);
1232 }
1233
David Andersoncf444f32018-08-29 14:15:49 -07001234 DetermineSecondarySlot();
1235 CollectImages();
David Anderson32e376f2018-08-16 13:43:11 -07001236
David Anderson95d40932018-08-28 12:14:33 -07001237 // First flash boot partitions. We allow this to happen either in userspace
1238 // or in bootloader fastboot.
David Andersoncf444f32018-08-29 14:15:49 -07001239 FlashImages(boot_images_);
David Anderson95d40932018-08-28 12:14:33 -07001240
1241 // Sync the super partition. This will reboot to userspace fastboot if needed.
David Andersoncf444f32018-08-29 14:15:49 -07001242 UpdateSuperPartition();
David Anderson95d40932018-08-28 12:14:33 -07001243
1244 // Resize any logical partition to 0, so each partition is reset to 0
1245 // extents, and will achieve more optimal allocation.
David Andersoncf444f32018-08-29 14:15:49 -07001246 for (const auto& [image, slot] : os_images_) {
David Anderson32e376f2018-08-16 13:43:11 -07001247 auto resize_partition = [](const std::string& partition) -> void {
1248 if (is_logical(partition)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001249 fb->ResizePartition(partition, "0");
David Anderson32e376f2018-08-16 13:43:11 -07001250 }
1251 };
David Anderson95d40932018-08-28 12:14:33 -07001252 do_for_partitions(image->part_name, slot, resize_partition, false);
David Anderson32e376f2018-08-16 13:43:11 -07001253 }
1254
David Anderson95d40932018-08-28 12:14:33 -07001255 // Flash OS images, resizing logical partitions as needed.
David Andersoncf444f32018-08-29 14:15:49 -07001256 FlashImages(os_images_);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001257}
1258
David Andersoncf444f32018-08-29 14:15:49 -07001259void FlashAllTool::CheckRequirements() {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001260 std::vector<char> contents;
1261 if (!source_.ReadFile("android-info.txt", &contents)) {
David Andersoncf444f32018-08-29 14:15:49 -07001262 die("could not read android-info.txt");
1263 }
Tom Cherry4aa60b32018-09-05 15:11:44 -07001264 ::CheckRequirements({contents.data(), contents.size()});
David Andersoncf444f32018-08-29 14:15:49 -07001265}
1266
1267void FlashAllTool::DetermineSecondarySlot() {
1268 if (skip_secondary_) {
1269 return;
1270 }
David Anderson96a9fd42018-11-05 15:21:44 -08001271 if (slot_override_ != "" && slot_override_ != "all") {
David Andersoncf444f32018-08-29 14:15:49 -07001272 secondary_slot_ = get_other_slot(slot_override_);
1273 } else {
1274 secondary_slot_ = get_other_slot();
1275 }
1276 if (secondary_slot_ == "") {
1277 if (supports_AB()) {
1278 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1279 }
1280 skip_secondary_ = true;
1281 }
1282}
1283
1284void FlashAllTool::CollectImages() {
1285 for (size_t i = 0; i < arraysize(images); ++i) {
1286 std::string slot = slot_override_;
1287 if (images[i].IsSecondary()) {
1288 if (skip_secondary_) {
1289 continue;
1290 }
1291 slot = secondary_slot_;
1292 }
1293 if (images[i].type == ImageType::BootCritical) {
1294 boot_images_.emplace_back(&images[i], slot);
1295 } else if (images[i].type == ImageType::Normal) {
1296 os_images_.emplace_back(&images[i], slot);
1297 }
1298 }
1299}
1300
1301void FlashAllTool::FlashImages(const std::vector<std::pair<const Image*, std::string>>& images) {
1302 for (const auto& [image, slot] : images) {
1303 fastboot_buffer buf;
1304 int fd = source_.OpenFile(image->img_name);
1305 if (fd < 0 || !load_buf_fd(fd, &buf)) {
1306 if (image->optional_if_no_image) {
1307 continue;
1308 }
1309 die("could not load '%s': %s", image->img_name, strerror(errno));
1310 }
1311 FlashImage(*image, slot, &buf);
1312 }
1313}
1314
1315void FlashAllTool::FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf) {
1316 auto flash = [&, this](const std::string& partition_name) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001317 std::vector<char> signature_data;
1318 if (source_.ReadFile(image.sig_name, &signature_data)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001319 fb->Download("signature", signature_data);
1320 fb->RawCommand("signature", "installing signature");
David Andersoncf444f32018-08-29 14:15:49 -07001321 }
1322
1323 if (is_logical(partition_name)) {
Tom Cherry9027af02018-09-24 15:48:09 -07001324 fb->ResizePartition(partition_name, std::to_string(buf->image_size));
David Andersoncf444f32018-08-29 14:15:49 -07001325 }
1326 flash_buf(partition_name.c_str(), buf);
1327 };
1328 do_for_partitions(image.part_name, slot, flash, false);
1329}
1330
1331void FlashAllTool::UpdateSuperPartition() {
David Andersoncf444f32018-08-29 14:15:49 -07001332 int fd = source_.OpenFile("super_empty.img");
1333 if (fd < 0) {
1334 return;
1335 }
1336 if (!is_userspace_fastboot()) {
1337 reboot_to_userspace_fastboot();
1338 }
David Andersoncf444f32018-08-29 14:15:49 -07001339
David Anderson90fe0a42018-11-05 18:01:32 -08001340 std::string super_name;
1341 if (fb->GetVar("super-partition-name", &super_name) != fastboot::RetCode::SUCCESS) {
1342 super_name = "super";
1343 }
1344 fb->Download(super_name, fd, get_file_size(fd));
1345
1346 std::string command = "update-super:" + super_name;
David Andersoncf444f32018-08-29 14:15:49 -07001347 if (wipe_) {
1348 command += ":wipe";
1349 }
Tom Cherry9027af02018-09-24 15:48:09 -07001350 fb->RawCommand(command, "Updating super partition");
David Anderson0c732342018-11-28 17:10:42 -08001351
1352 // Retrofit devices have two super partitions, named super_a and super_b.
1353 // On these devices, secondary slots must be flashed as physical
1354 // partitions (otherwise they would not mount on first boot). To enforce
1355 // this, we delete any logical partitions for the "other" slot.
1356 if (is_retrofit_device()) {
1357 for (const auto& [image, slot] : os_images_) {
1358 std::string partition_name = image->part_name + "_"s + slot;
1359 if (image->IsSecondary() && is_logical(partition_name)) {
1360 fb->DeletePartition(partition_name);
1361 }
1362 }
1363 }
David Andersoncf444f32018-08-29 14:15:49 -07001364}
1365
1366class ZipImageSource final : public ImageSource {
1367 public:
1368 explicit ZipImageSource(ZipArchiveHandle zip) : zip_(zip) {}
Tom Cherrydfd85df2018-09-20 14:45:05 -07001369 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001370 int OpenFile(const std::string& name) const override;
1371
1372 private:
1373 ZipArchiveHandle zip_;
1374};
1375
Tom Cherrydfd85df2018-09-20 14:45:05 -07001376bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1377 return UnzipToMemory(zip_, name, out);
David Andersoncf444f32018-08-29 14:15:49 -07001378}
1379
1380int ZipImageSource::OpenFile(const std::string& name) const {
1381 return unzip_to_file(zip_, name.c_str());
1382}
1383
1384static void do_update(const char* filename, const std::string& slot_override, bool skip_secondary) {
David Andersoncf444f32018-08-29 14:15:49 -07001385 ZipArchiveHandle zip;
1386 int error = OpenArchive(filename, &zip);
1387 if (error != 0) {
1388 die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1389 }
1390
1391 FlashAllTool tool(ZipImageSource(zip), slot_override, skip_secondary, false);
1392 tool.Flash();
1393
1394 CloseArchive(zip);
1395}
1396
1397class LocalImageSource final : public ImageSource {
1398 public:
Tom Cherrydfd85df2018-09-20 14:45:05 -07001399 bool ReadFile(const std::string& name, std::vector<char>* out) const override;
David Andersoncf444f32018-08-29 14:15:49 -07001400 int OpenFile(const std::string& name) const override;
1401};
1402
Tom Cherrydfd85df2018-09-20 14:45:05 -07001403bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
David Andersoncf444f32018-08-29 14:15:49 -07001404 auto path = find_item_given_name(name);
1405 if (path.empty()) {
Tom Cherrydfd85df2018-09-20 14:45:05 -07001406 return false;
David Andersoncf444f32018-08-29 14:15:49 -07001407 }
Tom Cherrydfd85df2018-09-20 14:45:05 -07001408 return ReadFileToVector(path, out);
David Andersoncf444f32018-08-29 14:15:49 -07001409}
1410
1411int LocalImageSource::OpenFile(const std::string& name) const {
1412 auto path = find_item_given_name(name);
Hridya Valsaraju1a6f6fe2019-04-03 17:57:00 -07001413 return open(path.c_str(), O_RDONLY | O_BINARY);
David Andersoncf444f32018-08-29 14:15:49 -07001414}
1415
1416static void do_flashall(const std::string& slot_override, bool skip_secondary, bool wipe) {
David Andersoncf444f32018-08-29 14:15:49 -07001417 FlashAllTool tool(LocalImageSource(), slot_override, skip_secondary, wipe);
1418 tool.Flash();
1419}
1420
Elliott Hughesd6365a72017-05-08 18:04:49 -07001421static std::string next_arg(std::vector<std::string>* args) {
1422 if (args->empty()) syntax_error("expected argument");
1423 std::string result = args->front();
1424 args->erase(args->begin());
1425 return result;
Patrick Tjin51e8b032015-09-01 08:15:23 -07001426}
1427
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001428static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001429 if (args->empty()) syntax_error("empty oem command");
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001430
Elliott Hughes1eec97a2017-05-15 16:53:53 -07001431 std::string command(cmd);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001432 while (!args->empty()) {
Elliott Hughes29d5d7d2017-05-11 15:05:13 -07001433 command += " " + next_arg(args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001434 }
Tom Cherry9027af02018-09-24 15:48:09 -07001435 fb->RawCommand(command, "");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001436}
1437
Connor O'Brience16a8a2017-02-06 14:39:31 -08001438static std::string fb_fix_numeric_var(std::string var) {
1439 // Some bootloaders (angler, for example), send spurious leading whitespace.
1440 var = android::base::Trim(var);
1441 // Some bootloaders (hammerhead, for example) use implicit hex.
1442 // This code used to use strtol with base 16.
1443 if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
1444 return var;
1445}
1446
Aaron Wisnerdb511202018-06-26 15:38:35 -05001447static unsigned fb_get_flash_block_size(std::string name) {
Connor O'Brience16a8a2017-02-06 14:39:31 -08001448 std::string sizeString;
Tom Cherry9027af02018-09-24 15:48:09 -07001449 if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001450 // This device does not report flash block sizes, so return 0.
Connor O'Brience16a8a2017-02-06 14:39:31 -08001451 return 0;
1452 }
1453 sizeString = fb_fix_numeric_var(sizeString);
1454
1455 unsigned size;
1456 if (!android::base::ParseUint(sizeString, &size)) {
1457 fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1458 return 0;
1459 }
Connor O'Brien6ef5c242017-11-01 17:37:32 -07001460 if ((size & (size - 1)) != 0) {
1461 fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
Connor O'Brience16a8a2017-02-06 14:39:31 -08001462 return 0;
1463 }
1464 return size;
1465}
1466
Aaron Wisnerdb511202018-06-26 15:38:35 -05001467static void fb_perform_format(
Elliott Hughes5620d222018-03-28 08:20:00 -07001468 const std::string& partition, int skip_if_not_supported,
Elliott Hughesd6365a72017-05-08 18:04:49 -07001469 const std::string& type_override, const std::string& size_override,
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001470 const std::string& initial_dir) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001471 std::string partition_type, partition_size;
1472
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001473 struct fastboot_buffer buf;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001474 const char* errMsg = nullptr;
1475 const struct fs_generator* gen = nullptr;
Jin Qian4a335822017-04-18 16:23:18 -07001476 TemporaryFile output;
1477 unique_fd fd;
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001478
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001479 unsigned int limit = INT_MAX;
1480 if (target_sparse_limit > 0 && target_sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001481 limit = target_sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001482 }
1483 if (sparse_limit > 0 && sparse_limit < limit) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001484 limit = sparse_limit;
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001485 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001486
Tom Cherry9027af02018-09-24 15:48:09 -07001487 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001488 errMsg = "Can't determine partition type.\n";
1489 goto failed;
1490 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001491 if (!type_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001492 if (partition_type != type_override) {
1493 fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001494 partition.c_str(), partition_type.c_str(), type_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001495 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001496 partition_type = type_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001497 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001498
Tom Cherry9027af02018-09-24 15:48:09 -07001499 if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001500 errMsg = "Unable to get partition size\n";
1501 goto failed;
1502 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001503 if (!size_override.empty()) {
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001504 if (partition_size != size_override) {
1505 fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
Elliott Hughes5620d222018-03-28 08:20:00 -07001506 partition.c_str(), partition_size.c_str(), size_override.c_str());
JP Abgrall7e859742014-05-06 15:14:15 -07001507 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001508 partition_size = size_override;
JP Abgrall7e859742014-05-06 15:14:15 -07001509 }
Connor O'Brience16a8a2017-02-06 14:39:31 -08001510 partition_size = fb_fix_numeric_var(partition_size);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001511
Elliott Hughes8ab9a322015-11-02 14:05:57 -08001512 gen = fs_get_generator(partition_type);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001513 if (!gen) {
1514 if (skip_if_not_supported) {
1515 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001516 fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001517 return;
1518 }
Mark Salyzyna30b6962018-11-20 11:04:15 -08001519 die("Formatting is not supported for file system with type '%s'.",
1520 partition_type.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001521 }
1522
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001523 int64_t size;
Elliott Hughesda46b392016-10-11 17:09:00 -07001524 if (!android::base::ParseInt(partition_size, &size)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001525 die("Couldn't parse partition size '%s'.", partition_size.c_str());
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001526 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001527
Connor O'Brience16a8a2017-02-06 14:39:31 -08001528 unsigned eraseBlkSize, logicalBlkSize;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001529 eraseBlkSize = fb_get_flash_block_size("erase-block-size");
1530 logicalBlkSize = fb_get_flash_block_size("logical-block-size");
Connor O'Brience16a8a2017-02-06 14:39:31 -08001531
Jin Qian4a335822017-04-18 16:23:18 -07001532 if (fs_generator_generate(gen, output.path, size, initial_dir,
1533 eraseBlkSize, logicalBlkSize)) {
Elliott Hughes5620d222018-03-28 08:20:00 -07001534 die("Cannot generate image for %s", partition.c_str());
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001535 }
1536
Jin Qian4a335822017-04-18 16:23:18 -07001537 fd.reset(open(output.path, O_RDONLY));
1538 if (fd == -1) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001539 die("Cannot open generated image: %s", strerror(errno));
Jin Qian4a335822017-04-18 16:23:18 -07001540 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001541 if (!load_buf_fd(fd.release(), &buf)) {
Mark Salyzyna30b6962018-11-20 11:04:15 -08001542 die("Cannot read image: %s", strerror(errno));
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001543 }
1544 flash_buf(partition, &buf);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001545 return;
1546
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001547failed:
1548 if (skip_if_not_supported) {
1549 fprintf(stderr, "Erase successful, but not automatically formatting.\n");
Elliott Hughes2fd45a92015-10-30 11:49:47 -07001550 if (errMsg) fprintf(stderr, "%s", errMsg);
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001551 }
Tom Cherry9027af02018-09-24 15:48:09 -07001552 fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
Mark Salyzyna30b6962018-11-20 11:04:15 -08001553 if (!skip_if_not_supported) {
1554 die("Command failed");
1555 }
Dmitry Grinberge6f3e9b2014-03-11 18:28:15 -07001556}
1557
David Anderson89569642018-11-16 15:53:35 -08001558static bool should_flash_in_userspace(const std::string& partition_name) {
David Andersone0e693c2018-11-27 20:19:26 -08001559 if (!get_android_product_out()) {
1560 return false;
1561 }
David Anderson89569642018-11-16 15:53:35 -08001562 auto path = find_item_given_name("super_empty.img");
David Anderson00475802018-12-04 17:05:47 -08001563 if (path.empty() || access(path.c_str(), R_OK)) {
David Anderson89569642018-11-16 15:53:35 -08001564 return false;
1565 }
1566 auto metadata = android::fs_mgr::ReadFromImageFile(path);
1567 if (!metadata) {
1568 return false;
1569 }
1570 for (const auto& partition : metadata->partitions) {
1571 auto candidate = android::fs_mgr::GetPartitionName(partition);
1572 if (partition.attributes & LP_PARTITION_ATTR_SLOT_SUFFIXED) {
1573 // On retrofit devices, we don't know if, or whether, the A or B
1574 // slot has been flashed for dynamic partitions. Instead we add
1575 // both names to the list as a conservative guess.
1576 if (candidate + "_a" == partition_name || candidate + "_b" == partition_name) {
1577 return true;
1578 }
1579 } else if (candidate == partition_name) {
1580 return true;
1581 }
1582 }
1583 return false;
1584}
1585
David Anderson7c84b9f2019-06-27 22:15:29 -07001586static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
1587 std::string* message) {
1588 auto super_device = GetMetadataSuperBlockDevice(metadata);
1589 auto block_size = metadata.geometry.logical_block_size;
1590 auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
1591
1592 if (super_bdev_name != "super") {
1593 // retrofit devices do not allow flashing to the retrofit partitions,
1594 // so enable it if we can.
1595 fb->RawCommand("oem allow-flash-super");
1596 }
1597
1598 // Note: do not use die() in here, since we want TemporaryDir's destructor
1599 // to be called.
1600 TemporaryDir temp_dir;
1601
1602 bool ok;
1603 if (metadata.block_devices.size() > 1) {
1604 ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
1605 } else {
1606 auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
1607 ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
1608 }
1609 if (!ok) {
1610 *message = "Could not generate a flashable super image file";
1611 return false;
1612 }
1613
1614 for (const auto& block_device : metadata.block_devices) {
1615 auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
1616 bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
1617
1618 std::string image_name;
1619 if (metadata.block_devices.size() > 1) {
1620 image_name = "super_" + partition + ".img";
1621 } else {
1622 image_name = partition + ".img";
1623 }
1624
1625 auto image_path = temp_dir.path + "/"s + image_name;
1626 auto flash = [&](const std::string& partition_name) {
1627 do_flash(partition_name.c_str(), image_path.c_str());
1628 };
1629 do_for_partitions(partition, slot, flash, force_slot);
1630
1631 unlink(image_path.c_str());
1632 }
1633 return true;
1634}
1635
1636static void do_wipe_super(const std::string& image, const std::string& slot_override) {
1637 if (access(image.c_str(), R_OK) != 0) {
1638 die("Could not read image: %s", image.c_str());
1639 }
1640 auto metadata = android::fs_mgr::ReadFromImageFile(image);
1641 if (!metadata) {
1642 die("Could not parse image: %s", image.c_str());
1643 }
1644
1645 auto slot = slot_override;
1646 if (slot.empty()) {
1647 slot = get_current_slot();
1648 }
1649
1650 std::string message;
1651 if (!wipe_super(*metadata.get(), slot, &message)) {
1652 die(message);
1653 }
1654}
1655
Aaron Wisnerdb511202018-06-26 15:38:35 -05001656int FastBootTool::Main(int argc, char* argv[]) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001657 bool wants_wipe = false;
1658 bool wants_reboot = false;
1659 bool wants_reboot_bootloader = false;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001660 bool wants_reboot_recovery = false;
1661 bool wants_reboot_fastboot = false;
Mitchell Wills31dce302016-09-26 10:26:21 -07001662 bool skip_reboot = false;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001663 bool wants_set_active = false;
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001664 bool skip_secondary = false;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001665 bool set_fbe_marker = false;
David Anderson89569642018-11-16 15:53:35 -08001666 bool force_flash = false;
Florian Bäuerle27ded482014-11-24 11:29:34 +01001667 int longindex;
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001668 std::string slot_override;
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001669 std::string next_active;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001670
Elliott Hughes577e8b42018-04-05 16:12:47 -07001671 g_boot_img_hdr.kernel_addr = 0x00008000;
1672 g_boot_img_hdr.ramdisk_addr = 0x01000000;
1673 g_boot_img_hdr.second_addr = 0x00f00000;
1674 g_boot_img_hdr.tags_addr = 0x00000100;
1675 g_boot_img_hdr.page_size = 2048;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001676 g_boot_img_hdr.dtb_addr = 0x01100000;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001677
JP Abgrall7b8970c2013-03-07 17:06:41 -08001678 const struct option longopts[] = {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001679 {"base", required_argument, 0, 0},
1680 {"cmdline", required_argument, 0, 0},
1681 {"disable-verification", no_argument, 0, 0},
1682 {"disable-verity", no_argument, 0, 0},
David Anderson89569642018-11-16 15:53:35 -08001683 {"force", no_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001684 {"header-version", required_argument, 0, 0},
Elliott Hughes379646b2015-06-02 13:50:00 -07001685 {"help", no_argument, 0, 'h'},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001686 {"kernel-offset", required_argument, 0, 0},
1687 {"os-patch-level", required_argument, 0, 0},
1688 {"os-version", required_argument, 0, 0},
1689 {"page-size", required_argument, 0, 0},
1690 {"ramdisk-offset", required_argument, 0, 0},
Daniel Rosenberg7aa38bc2015-11-11 17:29:37 -08001691 {"set-active", optional_argument, 0, 'a'},
Mitchell Wills31dce302016-09-26 10:26:21 -07001692 {"skip-reboot", no_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001693 {"skip-secondary", no_argument, 0, 0},
1694 {"slot", required_argument, 0, 0},
1695 {"tags-offset", required_argument, 0, 0},
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001696 {"dtb", required_argument, 0, 0},
1697 {"dtb-offset", required_argument, 0, 0},
Elliott Hughes577e8b42018-04-05 16:12:47 -07001698 {"unbuffered", no_argument, 0, 0},
Elliott Hughesf238d872018-03-29 14:46:29 -07001699 {"verbose", no_argument, 0, 'v'},
1700 {"version", no_argument, 0, 0},
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001701#if !defined(_WIN32)
1702 {"wipe-and-use-fbe", no_argument, 0, 0},
1703#endif
JP Abgrall7b8970c2013-03-07 17:06:41 -08001704 {0, 0, 0, 0}
1705 };
Colin Cross8879f982012-05-22 17:53:34 -07001706
1707 serial = getenv("ANDROID_SERIAL");
1708
Elliott Hughes577e8b42018-04-05 16:12:47 -07001709 int c;
Elliott Hughesf3192bd2018-04-10 15:38:08 -07001710 while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
Elliott Hughes577e8b42018-04-05 16:12:47 -07001711 if (c == 0) {
1712 std::string name{longopts[longindex].name};
1713 if (name == "base") {
1714 g_base_addr = strtoul(optarg, 0, 16);
1715 } else if (name == "cmdline") {
1716 g_cmdline = optarg;
1717 } else if (name == "disable-verification") {
1718 g_disable_verification = true;
1719 } else if (name == "disable-verity") {
1720 g_disable_verity = true;
David Anderson89569642018-11-16 15:53:35 -08001721 } else if (name == "force") {
1722 force_flash = true;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001723 } else if (name == "header-version") {
1724 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001725 } else if (name == "dtb") {
1726 g_dtb_path = optarg;
Elliott Hughes577e8b42018-04-05 16:12:47 -07001727 } else if (name == "kernel-offset") {
1728 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
1729 } else if (name == "os-patch-level") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001730 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001731 } else if (name == "os-version") {
Elliott Hughes6ebec932018-04-10 14:22:13 -07001732 ParseOsVersion(&g_boot_img_hdr, optarg);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001733 } else if (name == "page-size") {
1734 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
1735 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
1736 } else if (name == "ramdisk-offset") {
1737 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
1738 } else if (name == "skip-reboot") {
1739 skip_reboot = true;
1740 } else if (name == "skip-secondary") {
1741 skip_secondary = true;
1742 } else if (name == "slot") {
1743 slot_override = optarg;
Hridya Valsaraju6c8fca62019-01-24 12:47:08 -08001744 } else if (name == "dtb-offset") {
1745 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001746 } else if (name == "tags-offset") {
1747 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
1748 } else if (name == "unbuffered") {
Elliott Hughesfc797672015-04-07 20:12:50 -07001749 setvbuf(stdout, nullptr, _IONBF, 0);
1750 setvbuf(stderr, nullptr, _IONBF, 0);
Elliott Hughes577e8b42018-04-05 16:12:47 -07001751 } else if (name == "version") {
Dan Willemsenab971b52018-08-29 14:58:02 -07001752 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION, android::build::GetBuildNumber().c_str());
Elliott Hughes1fd46df2017-03-30 15:08:28 -07001753 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
Elliott Hughes379646b2015-06-02 13:50:00 -07001754 return 0;
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001755#if !defined(_WIN32)
Elliott Hughes577e8b42018-04-05 16:12:47 -07001756 } else if (name == "wipe-and-use-fbe") {
Paul Crowley8f7f56e2015-11-27 09:29:37 +00001757 wants_wipe = true;
1758 set_fbe_marker = true;
1759#endif
1760 } else {
Elliott Hughes855cdf82018-04-02 14:24:03 -07001761 die("unknown option %s", longopts[longindex].name);
Florian Bäuerle27ded482014-11-24 11:29:34 +01001762 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07001763 } else {
1764 switch (c) {
1765 case 'a':
1766 wants_set_active = true;
1767 if (optarg) next_active = optarg;
1768 break;
1769 case 'h':
1770 return show_help();
Elliott Hughes577e8b42018-04-05 16:12:47 -07001771 case 'l':
1772 g_long_listing = true;
1773 break;
1774 case 's':
1775 serial = optarg;
1776 break;
1777 case 'S':
Elliott Hughes542370d2018-04-19 19:49:44 -07001778 if (!android::base::ParseByteCount(optarg, &sparse_limit)) {
1779 die("invalid sparse limit %s", optarg);
1780 }
Elliott Hughes577e8b42018-04-05 16:12:47 -07001781 break;
1782 case 'v':
1783 set_verbose();
1784 break;
1785 case 'w':
1786 wants_wipe = true;
1787 break;
1788 case '?':
1789 return 1;
1790 default:
1791 abort();
1792 }
Colin Cross8879f982012-05-22 17:53:34 -07001793 }
1794 }
1795
1796 argc -= optind;
1797 argv += optind;
1798
Elliott Hughesd6365a72017-05-08 18:04:49 -07001799 if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001800
Colin Cross8fb6e062012-07-24 16:36:41 -07001801 if (argc > 0 && !strcmp(*argv, "devices")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001802 list_devices();
Tsu Chiang Chuangee520552011-02-25 18:38:53 -08001803 return 0;
1804 }
1805
Colin Crossc7b75dc2012-08-29 18:17:06 -07001806 if (argc > 0 && !strcmp(*argv, "help")) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001807 return show_help();
Colin Crossc7b75dc2012-08-29 18:17:06 -07001808 }
1809
David Pursell0b156632015-10-30 11:22:01 -07001810 Transport* transport = open_device();
David Pursell2ec418a2016-01-20 08:32:08 -08001811 if (transport == nullptr) {
1812 return 1;
1813 }
Tom Cherry9027af02018-09-24 15:48:09 -07001814 fastboot::DriverCallbacks driver_callbacks = {
1815 .prolog = Status,
1816 .epilog = Epilog,
1817 .info = InfoMessage,
1818 };
1819 fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
1820 fb = &fastboot_driver;
David Pursell2ec418a2016-01-20 08:32:08 -08001821
Elliott Hughes5620d222018-03-28 08:20:00 -07001822 const double start = now();
1823
Aaron Wisnerdb511202018-06-26 15:38:35 -05001824 if (slot_override != "") slot_override = verify_slot(slot_override);
1825 if (next_active != "") next_active = verify_slot(next_active, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001826
1827 if (wants_set_active) {
1828 if (next_active == "") {
1829 if (slot_override == "") {
Daniel Rosenberg13454092016-06-27 19:43:11 -07001830 std::string current_slot;
Tom Cherry9027af02018-09-24 15:48:09 -07001831 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001832 next_active = verify_slot(current_slot, false);
Daniel Rosenberg13454092016-06-27 19:43:11 -07001833 } else {
1834 wants_set_active = false;
1835 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001836 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001837 next_active = verify_slot(slot_override, false);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001838 }
1839 }
1840 }
Elliott Hughes31dbed72009-10-07 15:38:53 -07001841
Elliott Hughesd6365a72017-05-08 18:04:49 -07001842 std::vector<std::string> args(argv, argv + argc);
1843 while (!args.empty()) {
1844 std::string command = next_arg(&args);
Ken Sumrall5ee5d382012-09-29 14:46:25 -07001845
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001846 if (command == FB_CMD_GETVAR) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001847 std::string variable = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07001848 DisplayVarOrError(variable, variable);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001849 } else if (command == FB_CMD_ERASE) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001850 std::string partition = next_arg(&args);
1851 auto erase = [&](const std::string& partition) {
David Pursell0b156632015-10-30 11:22:01 -07001852 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07001853 if (fb->GetVar("partition-type:" + partition, &partition_type) == fastboot::SUCCESS &&
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001854 fs_get_generator(partition_type) != nullptr) {
1855 fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
1856 partition_type.c_str());
1857 }
Ken Sumrall5ee5d382012-09-29 14:46:25 -07001858
Tom Cherry9027af02018-09-24 15:48:09 -07001859 fb->Erase(partition);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001860 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05001861 do_for_partitions(partition, slot_override, erase, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001862 } else if (android::base::StartsWith(command, "format")) {
1863 // Parsing for: "format[:[type][:[size]]]"
1864 // Some valid things:
1865 // - select only the size, and leave default fs type:
1866 // format::0x4000000 userdata
1867 // - default fs type and size:
1868 // format userdata
1869 // format:: userdata
1870 std::vector<std::string> pieces = android::base::Split(command, ":");
1871 std::string type_override;
1872 if (pieces.size() > 1) type_override = pieces[1].c_str();
1873 std::string size_override;
1874 if (pieces.size() > 2) size_override = pieces[2].c_str();
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001875
Elliott Hughesd6365a72017-05-08 18:04:49 -07001876 std::string partition = next_arg(&args);
1877
1878 auto format = [&](const std::string& partition) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001879 fb_perform_format(partition, 0, type_override, size_override, "");
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001880 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07001881 do_for_partitions(partition, slot_override, format, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001882 } else if (command == "signature") {
1883 std::string filename = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07001884 std::vector<char> data;
1885 if (!ReadFileToVector(filename, &data)) {
1886 die("could not load '%s': %s", filename.c_str(), strerror(errno));
1887 }
1888 if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
Tom Cherry9027af02018-09-24 15:48:09 -07001889 fb->Download("signature", data);
1890 fb->RawCommand("signature", "installing signature");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001891 } else if (command == FB_CMD_REBOOT) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001892 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001893
1894 if (args.size() == 1) {
1895 std::string what = next_arg(&args);
1896 if (what == "bootloader") {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001897 wants_reboot = false;
1898 wants_reboot_bootloader = true;
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001899 } else if (what == "recovery") {
1900 wants_reboot = false;
1901 wants_reboot_recovery = true;
1902 } else if (what == "fastboot") {
1903 wants_reboot = false;
1904 wants_reboot_fastboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001905 } else {
1906 syntax_error("unknown reboot target %s", what.c_str());
Alexey Polyudove0bfb752017-01-03 19:39:13 -08001907 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001908
Elliott Hughesca85df02015-02-25 10:02:00 -08001909 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001910 if (!args.empty()) syntax_error("junk after reboot command");
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001911 } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001912 wants_reboot_bootloader = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001913 } else if (command == FB_CMD_REBOOT_RECOVERY) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001914 wants_reboot_recovery = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001915 } else if (command == FB_CMD_REBOOT_FASTBOOT) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001916 wants_reboot_fastboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001917 } else if (command == FB_CMD_CONTINUE) {
Tom Cherry9027af02018-09-24 15:48:09 -07001918 fb->Continue();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001919 } else if (command == FB_CMD_BOOT) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001920 std::string kernel = next_arg(&args);
1921 std::string ramdisk;
1922 if (!args.empty()) ramdisk = next_arg(&args);
1923 std::string second_stage;
1924 if (!args.empty()) second_stage = next_arg(&args);
Tom Cherrydfd85df2018-09-20 14:45:05 -07001925 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
Tom Cherry9027af02018-09-24 15:48:09 -07001926 fb->Download("boot.img", data);
1927 fb->Boot();
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001928 } else if (command == FB_CMD_FLASH) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001929 std::string pname = next_arg(&args);
1930
Elliott Hughes2810d002016-04-25 14:31:18 -07001931 std::string fname;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001932 if (!args.empty()) {
1933 fname = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001934 } else {
Elliott Hughes45964a82017-05-03 22:43:23 -07001935 fname = find_item(pname);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001936 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001937 if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001938
1939 auto flash = [&](const std::string &partition) {
David Anderson89569642018-11-16 15:53:35 -08001940 if (should_flash_in_userspace(partition) && !is_userspace_fastboot() &&
1941 !force_flash) {
1942 die("The partition you are trying to flash is dynamic, and "
1943 "should be flashed via fastbootd. Please run:\n"
1944 "\n"
1945 " fastboot reboot fastboot\n"
1946 "\n"
1947 "And try again. If you are intentionally trying to "
1948 "overwrite a fixed partition, use --force.");
1949 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001950 do_flash(partition.c_str(), fname.c_str());
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001951 };
Greg Kaiserb49d9e12019-03-26 12:04:05 -07001952 do_for_partitions(pname, slot_override, flash, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001953 } else if (command == "flash:raw") {
1954 std::string partition = next_arg(&args);
1955 std::string kernel = next_arg(&args);
1956 std::string ramdisk;
1957 if (!args.empty()) ramdisk = next_arg(&args);
1958 std::string second_stage;
1959 if (!args.empty()) second_stage = next_arg(&args);
1960
Tom Cherrydfd85df2018-09-20 14:45:05 -07001961 auto data = LoadBootableImage(kernel, ramdisk, second_stage);
1962 auto flashraw = [&data](const std::string& partition) {
Tom Cherry9027af02018-09-24 15:48:09 -07001963 fb->FlashPartition(partition, data);
Daniel Rosenbergb7bd4ae2015-09-14 21:05:41 -07001964 };
Aaron Wisnerdb511202018-06-26 15:38:35 -05001965 do_for_partitions(partition, slot_override, flashraw, true);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001966 } else if (command == "flashall") {
Alex Lightbb9b8a52016-06-29 09:26:44 -07001967 if (slot_override == "all") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001968 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
David Anderson32e376f2018-08-16 13:43:11 -07001969 do_flashall(slot_override, true, wants_wipe);
Alex Lightbb9b8a52016-06-29 09:26:44 -07001970 } else {
David Anderson32e376f2018-08-16 13:43:11 -07001971 do_flashall(slot_override, skip_secondary, wants_wipe);
Alex Lightbb9b8a52016-06-29 09:26:44 -07001972 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08001973 wants_reboot = true;
Elliott Hughesd6365a72017-05-08 18:04:49 -07001974 } else if (command == "update") {
Daniel Rosenberg92b44762016-07-13 20:03:25 -07001975 bool slot_all = (slot_override == "all");
1976 if (slot_all) {
1977 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
1978 }
Elliott Hughesd6365a72017-05-08 18:04:49 -07001979 std::string filename = "update.zip";
1980 if (!args.empty()) {
1981 filename = next_arg(&args);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001982 }
Aaron Wisnerdb511202018-06-26 15:38:35 -05001983 do_update(filename.c_str(), slot_override, skip_secondary || slot_all);
Mitchell Wills31dce302016-09-26 10:26:21 -07001984 wants_reboot = true;
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001985 } else if (command == FB_CMD_SET_ACTIVE) {
Aaron Wisnerdb511202018-06-26 15:38:35 -05001986 std::string slot = verify_slot(next_arg(&args), false);
Tom Cherry9027af02018-09-24 15:48:09 -07001987 fb->SetActive(slot);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001988 } else if (command == "stage") {
1989 std::string filename = next_arg(&args);
1990
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08001991 struct fastboot_buffer buf;
Aaron Wisnerdb511202018-06-26 15:38:35 -05001992 if (!load_buf(filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
Elliott Hughesd6365a72017-05-08 18:04:49 -07001993 die("cannot load '%s'", filename.c_str());
Jocelyn Bohr98cc2832017-01-26 19:20:53 -08001994 }
Tom Cherry9027af02018-09-24 15:48:09 -07001995 fb->Download(filename, buf.fd, buf.sz);
Elliott Hughesd6365a72017-05-08 18:04:49 -07001996 } else if (command == "get_staged") {
1997 std::string filename = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07001998 fb->Upload(filename);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07001999 } else if (command == FB_CMD_OEM) {
2000 do_oem_command(FB_CMD_OEM, &args);
Elliott Hughesd6365a72017-05-08 18:04:49 -07002001 } else if (command == "flashing") {
2002 if (args.empty()) {
2003 syntax_error("missing 'flashing' command");
2004 } else if (args.size() == 1 && (args[0] == "unlock" || args[0] == "lock" ||
2005 args[0] == "unlock_critical" ||
2006 args[0] == "lock_critical" ||
Elliott Hughes2e9b7792018-04-04 13:36:44 -07002007 args[0] == "get_unlock_ability")) {
Elliott Hughes1eec97a2017-05-15 16:53:53 -07002008 do_oem_command("flashing", &args);
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002009 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002010 syntax_error("unknown 'flashing' command %s", args[0].c_str());
Badhri Jagan Sridharanbf110952015-05-15 16:43:47 -07002011 }
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002012 } else if (command == FB_CMD_CREATE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002013 std::string partition = next_arg(&args);
2014 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002015 fb->CreatePartition(partition, size);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002016 } else if (command == FB_CMD_DELETE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002017 std::string partition = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002018 fb->DeletePartition(partition);
Mark Salyzyn8e7e9cb2018-08-29 10:44:33 -07002019 } else if (command == FB_CMD_RESIZE_PARTITION) {
David Anderson0d4277d2018-07-31 13:27:37 -07002020 std::string partition = next_arg(&args);
2021 std::string size = next_arg(&args);
Tom Cherry9027af02018-09-24 15:48:09 -07002022 fb->ResizePartition(partition, size);
David Anderson1d504e32019-01-15 14:38:20 -08002023 } else if (command == "gsi") {
David Anderson3d782d52019-01-29 13:09:49 -08002024 std::string arg = next_arg(&args);
2025 if (arg == "wipe") {
David Anderson1d504e32019-01-15 14:38:20 -08002026 fb->RawCommand("gsi:wipe", "wiping GSI");
David Anderson3d782d52019-01-29 13:09:49 -08002027 } else if (arg == "disable") {
David Anderson1d504e32019-01-15 14:38:20 -08002028 fb->RawCommand("gsi:disable", "disabling GSI");
2029 } else {
2030 syntax_error("expected 'wipe' or 'disable'");
2031 }
David Anderson7c84b9f2019-06-27 22:15:29 -07002032 } else if (command == "wipe-super") {
2033 std::string image;
2034 if (args.empty()) {
2035 image = find_item_given_name("super_empty.img");
2036 } else {
2037 image = next_arg(&args);
2038 }
2039 do_wipe_super(image, slot_override);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002040 } else {
Elliott Hughesd6365a72017-05-08 18:04:49 -07002041 syntax_error("unknown command %s", command.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002042 }
2043 }
2044
2045 if (wants_wipe) {
Paul Crowley4d170062018-04-24 17:06:30 -07002046 std::vector<std::string> partitions = { "userdata", "cache", "metadata" };
2047 for (const auto& partition : partitions) {
2048 std::string partition_type;
Tom Cherry9027af02018-09-24 15:48:09 -07002049 if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
2050 continue;
2051 }
Paul Crowley4d170062018-04-24 17:06:30 -07002052 if (partition_type.empty()) continue;
Tom Cherry9027af02018-09-24 15:48:09 -07002053 fb->Erase(partition);
Paul Crowley4d170062018-04-24 17:06:30 -07002054 if (partition == "userdata" && set_fbe_marker) {
2055 fprintf(stderr, "setting FBE marker on initial userdata...\n");
2056 std::string initial_userdata_dir = create_fbemarker_tmpdir();
Aaron Wisnerdb511202018-06-26 15:38:35 -05002057 fb_perform_format(partition, 1, "", "", initial_userdata_dir);
Paul Crowley4d170062018-04-24 17:06:30 -07002058 delete_fbemarker_tmpdir(initial_userdata_dir);
2059 } else {
Aaron Wisnerdb511202018-06-26 15:38:35 -05002060 fb_perform_format(partition, 1, "", "", "");
Paul Crowley4d170062018-04-24 17:06:30 -07002061 }
Elliott Hughes2fd45a92015-10-30 11:49:47 -07002062 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002063 }
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002064 if (wants_set_active) {
Tom Cherry9027af02018-09-24 15:48:09 -07002065 fb->SetActive(next_active);
Daniel Rosenberg0d088562015-11-11 16:15:30 -08002066 }
Mitchell Wills31dce302016-09-26 10:26:21 -07002067 if (wants_reboot && !skip_reboot) {
Tom Cherry9027af02018-09-24 15:48:09 -07002068 fb->Reboot();
2069 fb->WaitForDisconnect();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002070 } else if (wants_reboot_bootloader) {
Tom Cherry9027af02018-09-24 15:48:09 -07002071 fb->RebootTo("bootloader");
2072 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002073 } else if (wants_reboot_recovery) {
Tom Cherry9027af02018-09-24 15:48:09 -07002074 fb->RebootTo("recovery");
2075 fb->WaitForDisconnect();
Hridya Valsarajudea91b42018-07-17 11:14:01 -07002076 } else if (wants_reboot_fastboot) {
David Anderson11d6d272018-12-07 16:39:07 -08002077 reboot_to_userspace_fastboot();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002078 }
2079
Elliott Hughes5620d222018-03-28 08:20:00 -07002080 fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
David Anderson03de6452018-09-04 14:32:54 -07002081
Tom Cherry9027af02018-09-24 15:48:09 -07002082 auto* old_transport = fb->set_transport(nullptr);
2083 delete old_transport;
2084
Tom Cherry11f12092018-08-29 21:36:28 -07002085 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002086}
Elliott Hughes6ebec932018-04-10 14:22:13 -07002087
Aaron Wisnerdb511202018-06-26 15:38:35 -05002088void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002089 unsigned year, month, day;
2090 if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2091 syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2092 }
2093 if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2094 if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2095 hdr->SetOsPatchLevel(year, month);
2096}
2097
Aaron Wisnerdb511202018-06-26 15:38:35 -05002098void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
Elliott Hughes6ebec932018-04-10 14:22:13 -07002099 unsigned major = 0, minor = 0, patch = 0;
2100 std::vector<std::string> versions = android::base::Split(arg, ".");
2101 if (versions.size() < 1 || versions.size() > 3 ||
2102 (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2103 (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2104 (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2105 (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2106 syntax_error("bad OS version: %s", arg);
2107 }
2108 hdr->SetOsVersion(major, minor, patch);
2109}