blob: 0a72812c2fc5a700af7495afe8a8c9fe18e99221 [file] [log] [blame]
Hridya Valsarajudea91b42018-07-17 11:14:01 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "commands.h"
18
Yifan Honga4eb4752021-02-16 19:37:21 -080019#include <inttypes.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070020#include <sys/socket.h>
21#include <sys/un.h>
22
David Anderson220ddb12019-10-31 18:02:41 -070023#include <unordered_set>
24
Hridya Valsarajudea91b42018-07-17 11:14:01 -070025#include <android-base/logging.h>
26#include <android-base/parseint.h>
27#include <android-base/properties.h>
28#include <android-base/stringprintf.h>
29#include <android-base/strings.h>
30#include <android-base/unique_fd.h>
David Andersonab8f4662019-10-21 16:45:59 -070031#include <android/hardware/boot/1.1/IBootControl.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070032#include <cutils/android_reboot.h>
David Anderson12211d12018-07-24 15:21:20 -070033#include <ext4_utils/wipe.h>
David Anderson5cbd2e42018-09-27 10:53:04 -070034#include <fs_mgr.h>
David Anderson2ffc31b2020-03-23 23:43:45 -070035#include <fs_mgr/roots.h>
David Anderson1d504e32019-01-15 14:38:20 -080036#include <libgsi/libgsi.h>
David Anderson0d4277d2018-07-31 13:27:37 -070037#include <liblp/builder.h>
38#include <liblp/liblp.h>
David Anderson220ddb12019-10-31 18:02:41 -070039#include <libsnapshot/snapshot.h>
Yifan Honga4eb4752021-02-16 19:37:21 -080040#include <storage_literals/storage_literals.h>
David Anderson0d4277d2018-07-31 13:27:37 -070041#include <uuid/uuid.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070042
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070043#include "constants.h"
Hridya Valsarajudea91b42018-07-17 11:14:01 -070044#include "fastboot_device.h"
David Anderson12211d12018-07-24 15:21:20 -070045#include "flashing.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070046#include "utility.h"
47
Yifan Honga4eb4752021-02-16 19:37:21 -080048#ifdef FB_ENABLE_FETCH
49static constexpr bool kEnableFetch = true;
50#else
51static constexpr bool kEnableFetch = false;
52#endif
53
David Anderson27475322019-06-11 14:00:08 -070054using android::fs_mgr::MetadataBuilder;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070055using ::android::hardware::hidl_string;
56using ::android::hardware::boot::V1_0::BoolResult;
57using ::android::hardware::boot::V1_0::CommandResult;
58using ::android::hardware::boot::V1_0::Slot;
David Andersonab8f4662019-10-21 16:45:59 -070059using ::android::hardware::boot::V1_1::MergeStatus;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070060using ::android::hardware::fastboot::V1_0::Result;
61using ::android::hardware::fastboot::V1_0::Status;
David Anderson220ddb12019-10-31 18:02:41 -070062using android::snapshot::SnapshotManager;
David Andersonab8f4662019-10-21 16:45:59 -070063using IBootControl1_1 = ::android::hardware::boot::V1_1::IBootControl;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070064
Yifan Honga4eb4752021-02-16 19:37:21 -080065using namespace android::storage_literals;
66
David Anderson0f626632018-08-31 16:44:25 -070067struct VariableHandlers {
68 // Callback to retrieve the value of a single variable.
69 std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
70 // Callback to retrieve all possible argument combinations, for getvar all.
71 std::function<std::vector<std::vector<std::string>>(FastbootDevice*)> get_all_args;
72};
73
David Anderson220ddb12019-10-31 18:02:41 -070074static bool IsSnapshotUpdateInProgress(FastbootDevice* device) {
75 auto hal = device->boot1_1();
76 if (!hal) {
77 return false;
78 }
79 auto merge_status = hal->getSnapshotMergeStatus();
80 return merge_status == MergeStatus::SNAPSHOTTED || merge_status == MergeStatus::MERGING;
81}
82
83static bool IsProtectedPartitionDuringMerge(FastbootDevice* device, const std::string& name) {
84 static const std::unordered_set<std::string> ProtectedPartitionsDuringMerge = {
85 "userdata", "metadata", "misc"};
86 if (ProtectedPartitionsDuringMerge.count(name) == 0) {
87 return false;
88 }
89 return IsSnapshotUpdateInProgress(device);
90}
91
David Anderson0f626632018-08-31 16:44:25 -070092static void GetAllVars(FastbootDevice* device, const std::string& name,
93 const VariableHandlers& handlers) {
94 if (!handlers.get_all_args) {
95 std::string message;
96 if (!handlers.get(device, std::vector<std::string>(), &message)) {
97 return;
98 }
99 device->WriteInfo(android::base::StringPrintf("%s:%s", name.c_str(), message.c_str()));
100 return;
101 }
102
103 auto all_args = handlers.get_all_args(device);
104 for (const auto& args : all_args) {
105 std::string message;
106 if (!handlers.get(device, args, &message)) {
107 continue;
108 }
109 std::string arg_string = android::base::Join(args, ":");
110 device->WriteInfo(android::base::StringPrintf("%s:%s:%s", name.c_str(), arg_string.c_str(),
111 message.c_str()));
112 }
113}
114
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700115bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson0f626632018-08-31 16:44:25 -0700116 const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
117 {FB_VAR_VERSION, {GetVersion, nullptr}},
118 {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
119 {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
Bowgo Tsai99f9a382020-01-21 18:31:23 +0800120 {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
121 {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
David Anderson0f626632018-08-31 16:44:25 -0700122 {FB_VAR_PRODUCT, {GetProduct, nullptr}},
123 {FB_VAR_SERIALNO, {GetSerial, nullptr}},
Hridya Valsaraju4af80902018-09-26 13:08:16 -0700124 {FB_VAR_VARIANT, {GetVariant, nullptr}},
David Anderson0f626632018-08-31 16:44:25 -0700125 {FB_VAR_SECURE, {GetSecure, nullptr}},
126 {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
127 {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
128 {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
129 {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
130 {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
131 {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
132 {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
David Anderson27475322019-06-11 14:00:08 -0700133 {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
Hridya Valsarajubf9f8d12018-09-05 16:57:24 -0700134 {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
David Anderson0f626632018-08-31 16:44:25 -0700135 {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
David Andersonc091c172018-09-04 18:11:03 -0700136 {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
Hridya Valsaraju7c9bbe92018-09-27 10:41:01 -0700137 {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
Hridya Valsaraju47658ca2018-09-28 11:41:22 -0700138 {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
Hridya Valsarajua534a5a2018-10-03 15:53:22 -0700139 {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
David Anderson90fe0a42018-11-05 18:01:32 -0800140 {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
David Andersonab8f4662019-10-21 16:45:59 -0700141 {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
Bowgo Tsai33da5c92019-11-13 17:13:49 +0800142 {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
Bowgo Tsai99f9a382020-01-21 18:31:23 +0800143 {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
144 {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
145 {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
146 {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
147 {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
148 {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
Yifan Hongb299cb72021-02-17 13:44:49 -0800149 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
150 {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
151 };
David Anderson0f626632018-08-31 16:44:25 -0700152
153 if (args.size() < 2) {
154 return device->WriteFail("Missing argument");
155 }
156
157 // Special case: return all variables that we can.
158 if (args[1] == "all") {
159 for (const auto& [name, handlers] : kVariableMap) {
160 GetAllVars(device, name, handlers);
161 }
162 return device->WriteOkay("");
163 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700164
165 // args[0] is command name, args[1] is variable.
166 auto found_variable = kVariableMap.find(args[1]);
167 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700168 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700169 }
170
David Anderson1fb3fd72018-08-31 14:40:22 -0700171 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700172 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700173 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700174 return device->WriteFail(message);
175 }
176 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700177}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700178
josephjang29069752020-09-23 16:28:03 +0800179bool OemPostWipeData(FastbootDevice* device) {
180 auto fastboot_hal = device->fastboot_hal();
181 if (!fastboot_hal) {
182 return false;
183 }
184
185 Result ret;
186 auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
187 if (!ret_val.isOk()) {
188 return false;
189 }
190 if (ret.status == Status::NOT_SUPPORTED) {
191 return false;
192 } else if (ret.status != Status::SUCCESS) {
193 device->WriteStatus(FastbootResult::FAIL, ret.message);
194 } else {
195 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
196 }
197
198 return true;
199}
200
David Anderson12211d12018-07-24 15:21:20 -0700201bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
202 if (args.size() < 2) {
203 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
204 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700205
206 if (GetDeviceLockStatus()) {
207 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
208 }
209
David Anderson220ddb12019-10-31 18:02:41 -0700210 const auto& partition_name = args[1];
211 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
212 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
213 return device->WriteFail(message);
214 }
215
David Anderson12211d12018-07-24 15:21:20 -0700216 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700217 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700218 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
219 }
220 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800221 //Perform oem PostWipeData if Android userdata partition has been erased
222 bool support_oem_postwipedata = false;
223 if (partition_name == "userdata") {
224 support_oem_postwipedata = OemPostWipeData(device);
225 }
226
227 if (!support_oem_postwipedata) {
228 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
229 } else {
230 //Write device status in OemPostWipeData(), so just return true
231 return true;
232 }
David Anderson12211d12018-07-24 15:21:20 -0700233 }
234 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
235}
236
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700237bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
238 auto fastboot_hal = device->fastboot_hal();
239 if (!fastboot_hal) {
240 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
241 }
242
josephjangad90b452020-09-16 16:27:42 +0800243 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
244 if (args[0] == "oem postwipedata userdata") {
245 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
246 }
247
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700248 Result ret;
249 auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
250 if (!ret_val.isOk()) {
251 return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
252 }
253 if (ret.status != Status::SUCCESS) {
254 return device->WriteStatus(FastbootResult::FAIL, ret.message);
255 }
256
257 return device->WriteStatus(FastbootResult::OKAY, ret.message);
258}
259
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700260bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
261 if (args.size() < 2) {
262 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
263 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700264
265 if (GetDeviceLockStatus()) {
266 return device->WriteStatus(FastbootResult::FAIL,
267 "Download is not allowed on locked devices");
268 }
269
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700270 // arg[0] is the command name, arg[1] contains size of data to be downloaded
271 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700272 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700273 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
274 }
David Anderson12211d12018-07-24 15:21:20 -0700275 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700276 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
277 return false;
278 }
279
David Anderson12211d12018-07-24 15:21:20 -0700280 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700281 return device->WriteStatus(FastbootResult::OKAY, "");
282 }
283
284 PLOG(ERROR) << "Couldn't download data";
285 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
286}
287
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700288bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
289 if (args.size() < 2) {
290 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
291 }
292
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700293 if (GetDeviceLockStatus()) {
294 return device->WriteStatus(FastbootResult::FAIL,
295 "set_active command is not allowed on locked devices");
296 }
297
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700298 Slot slot;
299 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700300 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700301 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
302 }
303
304 // Non-A/B devices will not have a boot control HAL.
305 auto boot_control_hal = device->boot_control_hal();
306 if (!boot_control_hal) {
307 return device->WriteStatus(FastbootResult::FAIL,
308 "Cannot set slot: boot control HAL absent");
309 }
310 if (slot >= boot_control_hal->getNumberSlots()) {
311 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
312 }
David Anderson220ddb12019-10-31 18:02:41 -0700313
314 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800315 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700316 return device->WriteOkay("");
317 }
318
319 // Check how to handle the current snapshot state.
320 if (auto hal11 = device->boot1_1()) {
321 auto merge_status = hal11->getSnapshotMergeStatus();
322 if (merge_status == MergeStatus::MERGING) {
323 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
324 }
325 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
326 // stage init does not have access to the HAL, and uses the slot number
327 // and /metadata OTA state to determine whether a slot change occurred.
328 // Booting into the old slot would erase the OTA, and switching A->B->A
329 // would simply resume it if no boots occur in between. Re-flashing
330 // partitions implicitly cancels the OTA, so leaving the state as-is is
331 // safe.
332 if (merge_status == MergeStatus::SNAPSHOTTED) {
333 device->WriteInfo(
334 "Changing the active slot with a snapshot applied may cancel the"
335 " update.");
336 }
337 }
338
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700339 CommandResult ret;
340 auto cb = [&ret](CommandResult result) { ret = result; };
341 auto result = boot_control_hal->setActiveBootSlot(slot, cb);
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700342 if (result.isOk() && ret.success) {
343 // Save as slot suffix to match the suffix format as returned from
344 // the boot control HAL.
345 auto current_slot = "_" + args[1];
346 device->set_active_slot(current_slot);
347 return device->WriteStatus(FastbootResult::OKAY, "");
348 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700349 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700350}
351
352bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
353 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
354 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
355 device->CloseDevice();
356 TEMP_FAILURE_RETRY(pause());
357 return result;
358}
359
360bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
361 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
362 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
363 device->CloseDevice();
364 TEMP_FAILURE_RETRY(pause());
365 return result;
366}
367
368bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
369 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
370 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
371 device->CloseDevice();
372 TEMP_FAILURE_RETRY(pause());
373 return result;
374}
375
376bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
377 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
378 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
379 device->CloseDevice();
380 TEMP_FAILURE_RETRY(pause());
381 return result;
382}
383
384static bool EnterRecovery() {
385 const char msg_switch_to_recovery = 'r';
386
387 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
388 if (sock < 0) {
389 PLOG(ERROR) << "Couldn't create sock";
390 return false;
391 }
392
393 struct sockaddr_un addr = {.sun_family = AF_UNIX};
394 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
Yifan Hong07e947f2021-03-22 19:21:34 -0700395 if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700396 PLOG(ERROR) << "Couldn't connect to recovery";
397 return false;
398 }
399 // Switch to recovery will not update the boot reason since it does not
400 // require a reboot.
Yifan Hong07e947f2021-03-22 19:21:34 -0700401 auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700402 if (ret != sizeof(msg_switch_to_recovery)) {
403 PLOG(ERROR) << "Couldn't write message to switch to recovery";
404 return false;
405 }
406
407 return true;
408}
409
410bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
411 auto status = true;
412 if (EnterRecovery()) {
413 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
414 } else {
415 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
416 }
417 device->CloseDevice();
418 TEMP_FAILURE_RETRY(pause());
419 return status;
420}
David Anderson0d4277d2018-07-31 13:27:37 -0700421
422// Helper class for opening a handle to a MetadataBuilder and writing the new
423// partition table to the same place it was read.
424class PartitionBuilder {
425 public:
David Andersond25f1c32018-11-09 20:41:33 -0800426 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700427
428 bool Write();
429 bool Valid() const { return !!builder_; }
430 MetadataBuilder* operator->() const { return builder_.get(); }
431
432 private:
David Anderson4d307b02018-12-17 17:07:34 -0800433 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700434 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800435 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700436 std::unique_ptr<MetadataBuilder> builder_;
437};
438
David Anderson4d307b02018-12-17 17:07:34 -0800439PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
440 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800441 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700442 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800443 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700444 if (!super_device) {
445 return;
446 }
447 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800448 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700449}
450
451bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700452 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700453 if (!metadata) {
454 return false;
455 }
David Anderson4d307b02018-12-17 17:07:34 -0800456 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700457}
458
459bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
460 if (args.size() < 3) {
461 return device->WriteFail("Invalid partition name and size");
462 }
463
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700464 if (GetDeviceLockStatus()) {
465 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
466 }
467
David Anderson0d4277d2018-07-31 13:27:37 -0700468 uint64_t partition_size;
469 std::string partition_name = args[1];
470 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
471 return device->WriteFail("Invalid partition size");
472 }
473
David Andersond25f1c32018-11-09 20:41:33 -0800474 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700475 if (!builder.Valid()) {
476 return device->WriteFail("Could not open super partition");
477 }
478 // TODO(112433293) Disallow if the name is in the physical table as well.
479 if (builder->FindPartition(partition_name)) {
480 return device->WriteFail("Partition already exists");
481 }
482
David Anderson27475322019-06-11 14:00:08 -0700483 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700484 if (!partition) {
485 return device->WriteFail("Failed to add partition");
486 }
487 if (!builder->ResizePartition(partition, partition_size)) {
488 builder->RemovePartition(partition_name);
489 return device->WriteFail("Not enough space for partition");
490 }
491 if (!builder.Write()) {
492 return device->WriteFail("Failed to write partition table");
493 }
494 return device->WriteOkay("Partition created");
495}
496
497bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
498 if (args.size() < 2) {
499 return device->WriteFail("Invalid partition name and size");
500 }
501
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700502 if (GetDeviceLockStatus()) {
503 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
504 }
505
David Andersond25f1c32018-11-09 20:41:33 -0800506 std::string partition_name = args[1];
507
508 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700509 if (!builder.Valid()) {
510 return device->WriteFail("Could not open super partition");
511 }
David Andersond25f1c32018-11-09 20:41:33 -0800512 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700513 if (!builder.Write()) {
514 return device->WriteFail("Failed to write partition table");
515 }
516 return device->WriteOkay("Partition deleted");
517}
518
519bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
520 if (args.size() < 3) {
521 return device->WriteFail("Invalid partition name and size");
522 }
523
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700524 if (GetDeviceLockStatus()) {
525 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
526 }
527
David Anderson0d4277d2018-07-31 13:27:37 -0700528 uint64_t partition_size;
529 std::string partition_name = args[1];
530 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
531 return device->WriteFail("Invalid partition size");
532 }
533
David Andersond25f1c32018-11-09 20:41:33 -0800534 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700535 if (!builder.Valid()) {
536 return device->WriteFail("Could not open super partition");
537 }
538
David Anderson27475322019-06-11 14:00:08 -0700539 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700540 if (!partition) {
541 return device->WriteFail("Partition does not exist");
542 }
David Andersonad970fc2019-08-27 14:01:16 -0700543
544 // Remove the updated flag to cancel any snapshots.
545 uint32_t attrs = partition->attributes();
546 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
547
David Anderson0d4277d2018-07-31 13:27:37 -0700548 if (!builder->ResizePartition(partition, partition_size)) {
549 return device->WriteFail("Not enough space to resize partition");
550 }
551 if (!builder.Write()) {
552 return device->WriteFail("Failed to write partition table");
553 }
554 return device->WriteOkay("Partition resized");
555}
David Anderson38b3c7a2018-08-15 16:27:42 -0700556
David Andersonad970fc2019-08-27 14:01:16 -0700557void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
558 PartitionBuilder builder(device, partition_name);
559 if (!builder.Valid()) return;
560
561 auto partition = builder->FindPartition(partition_name);
562 if (!partition) return;
563
564 // Remove the updated flag to cancel any snapshots.
565 uint32_t attrs = partition->attributes();
566 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
567
568 builder.Write();
569}
570
571bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
572 if (args.size() < 2) {
573 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
574 }
575
576 if (GetDeviceLockStatus()) {
577 return device->WriteStatus(FastbootResult::FAIL,
578 "Flashing is not allowed on locked devices");
579 }
580
581 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700582 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
583 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
584 return device->WriteFail(message);
585 }
586
David Andersonad970fc2019-08-27 14:01:16 -0700587 if (LogicalPartitionExists(device, partition_name)) {
588 CancelPartitionSnapshot(device, partition_name);
589 }
590
591 int ret = Flash(device, partition_name);
592 if (ret < 0) {
593 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
594 }
595 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
596}
597
David Anderson38b3c7a2018-08-15 16:27:42 -0700598bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
599 if (args.size() < 2) {
600 return device->WriteFail("Invalid arguments");
601 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700602
603 if (GetDeviceLockStatus()) {
604 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
605 }
606
David Anderson38b3c7a2018-08-15 16:27:42 -0700607 bool wipe = (args.size() >= 3 && args[2] == "wipe");
608 return UpdateSuper(device, args[1], wipe);
609}
David Anderson1d504e32019-01-15 14:38:20 -0800610
David Anderson3d782d52019-01-29 13:09:49 -0800611bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800612 if (args.size() != 2) {
613 return device->WriteFail("Invalid arguments");
614 }
David Anderson3d782d52019-01-29 13:09:49 -0800615
616 AutoMountMetadata mount_metadata;
617 if (!mount_metadata) {
618 return device->WriteFail("Could not find GSI install");
619 }
620
621 if (!android::gsi::IsGsiInstalled()) {
622 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
623 }
624
David Anderson1d504e32019-01-15 14:38:20 -0800625 if (args[1] == "wipe") {
626 if (!android::gsi::UninstallGsi()) {
627 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
628 }
629 } else if (args[1] == "disable") {
630 if (!android::gsi::DisableGsi()) {
631 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
632 }
633 }
634 return device->WriteStatus(FastbootResult::OKAY, "Success");
635}
David Andersonab8f4662019-10-21 16:45:59 -0700636
637bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
638 // Note that we use the HAL rather than mounting /metadata, since we want
639 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700640 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700641 if (!hal) return device->WriteFail("Not supported");
642
David Andersonab8f4662019-10-21 16:45:59 -0700643 // If no arguments, return the same thing as a getvar. Note that we get the
644 // HAL first so we can return "not supported" before we return the less
645 // specific error message below.
646 if (args.size() < 2 || args[1].empty()) {
647 std::string message;
648 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
649 return device->WriteFail("Could not determine update status");
650 }
651 device->WriteInfo(message);
652 return device->WriteOkay("");
653 }
654
David Anderson220ddb12019-10-31 18:02:41 -0700655 MergeStatus status = hal->getSnapshotMergeStatus();
656
657 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700658 return device->WriteFail("Invalid arguments");
659 }
David Anderson220ddb12019-10-31 18:02:41 -0700660 if (args[1] == "cancel") {
661 switch (status) {
662 case MergeStatus::SNAPSHOTTED:
663 case MergeStatus::MERGING:
664 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
665 break;
666 default:
667 break;
668 }
669 } else if (args[1] == "merge") {
670 if (status != MergeStatus::MERGING) {
671 return device->WriteFail("No snapshot merge is in progress");
672 }
David Andersonab8f4662019-10-21 16:45:59 -0700673
David Anderson565577f2021-02-04 20:14:18 -0800674 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700675 if (!sm) {
676 return device->WriteFail("Unable to create SnapshotManager");
677 }
David Anderson5a0177d2020-04-30 18:53:23 -0700678 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700679 return device->WriteFail("Unable to finish snapshot merge");
680 }
681 } else {
682 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700683 }
684 return device->WriteStatus(FastbootResult::OKAY, "Success");
685}
Yifan Honga4eb4752021-02-16 19:37:21 -0800686
687namespace {
688// Helper of FetchHandler.
689class PartitionFetcher {
690 public:
691 static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
692 if constexpr (!kEnableFetch) {
693 return device->WriteFail("Fetch is not allowed on user build");
694 }
695
696 if (GetDeviceLockStatus()) {
697 return device->WriteFail("Fetch is not allowed on locked devices");
698 }
699
700 PartitionFetcher fetcher(device, args);
701 if (fetcher.Open()) {
702 fetcher.Fetch();
703 }
704 CHECK(fetcher.ret_.has_value());
705 return *fetcher.ret_;
706 }
707
708 private:
709 PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
710 : device_(device), args_(&args) {}
711 // Return whether the partition is successfully opened.
712 // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
713 // that FetchHandler should return.
714 bool Open() {
Yifan Hongbcd27702021-02-16 19:37:32 -0800715 if (args_->size() < 2) {
716 ret_ = device_->WriteFail("Missing partition arg");
Yifan Honga4eb4752021-02-16 19:37:21 -0800717 return false;
718 }
719
Yifan Hongbcd27702021-02-16 19:37:32 -0800720 partition_name_ = args_->at(1);
721 if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
722 kAllowedPartitions.end()) {
723 ret_ = device_->WriteFail("Fetch is only allowed on [" +
724 android::base::Join(kAllowedPartitions, ", ") + "]");
725 return false;
726 }
727
728 if (!OpenPartition(device_, partition_name_, &handle_, true /* read */)) {
Yifan Honga4eb4752021-02-16 19:37:21 -0800729 ret_ = device_->WriteFail(
730 android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
731 return false;
732 }
733
734 partition_size_ = get_block_device_size(handle_.fd());
735 if (partition_size_ == 0) {
736 ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
737 partition_name_.c_str()));
738 return false;
739 }
740
741 start_offset_ = 0;
742 if (args_->size() >= 3) {
743 if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
744 ret_ = device_->WriteFail("Invalid offset, must be integer");
745 return false;
746 }
747 if (start_offset_ > std::numeric_limits<off64_t>::max()) {
748 ret_ = device_->WriteFail(
749 android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
750 return false;
751 }
752 }
753 if (start_offset_ > partition_size_) {
754 ret_ = device_->WriteFail(android::base::StringPrintf(
755 "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
756 partition_name_.c_str(), partition_size_));
757 return false;
758 }
759 uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
760 total_size_to_read_ = maximum_total_size_to_read;
761 if (args_->size() >= 4) {
762 if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
763 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
764 return false;
765 }
766 }
767 if (total_size_to_read_ == 0) {
768 ret_ = device_->WriteOkay("Read 0 bytes");
769 return false;
770 }
771 if (total_size_to_read_ > maximum_total_size_to_read) {
772 ret_ = device_->WriteFail(android::base::StringPrintf(
773 "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
774 " and fetching from offset 0x%" PRIx64,
775 total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
776 return false;
777 }
778
779 if (total_size_to_read_ > kMaxFetchSizeDefault) {
780 ret_ = device_->WriteFail(android::base::StringPrintf(
781 "Cannot fetch 0x%" PRIx64
782 " bytes because it exceeds maximum transport size 0x%x",
783 partition_size_, kMaxDownloadSizeDefault));
784 return false;
785 }
786
787 return true;
788 }
789
790 // Assume Open() returns true.
791 // After execution, ret_ is set to the value that FetchHandler should return.
792 void Fetch() {
793 CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
794 if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
795 ret_ = device_->WriteFail(android::base::StringPrintf(
796 "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
797 start_offset_, strerror(errno)));
798 return;
799 }
800
801 if (!device_->WriteStatus(FastbootResult::DATA,
802 android::base::StringPrintf(
803 "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
804 ret_ = false;
805 return;
806 }
807 uint64_t end_offset = start_offset_ + total_size_to_read_;
808 std::vector<char> buf(1_MiB);
809 uint64_t current_offset = start_offset_;
810 while (current_offset < end_offset) {
811 // On any error, exit. We can't return a status message to the driver because
812 // we are in the middle of writing data, so just let the driver guess what's wrong
813 // by ending the data stream prematurely.
814 uint64_t remaining = end_offset - current_offset;
815 uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
816 if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
817 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
818 << partition_name_ << " @ offset 0x" << current_offset;
819 ret_ = false;
820 return;
821 }
822 if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
823 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
824 << partition_name_ << " @ offset 0x" << current_offset;
825 ret_ = false;
826 return;
827 }
828 current_offset += chunk_size;
829 }
830
831 ret_ = device_->WriteOkay(android::base::StringPrintf(
832 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
833 start_offset_, total_size_to_read_));
834 }
835
Yifan Hongbcd27702021-02-16 19:37:32 -0800836 static constexpr std::array<const char*, 3> kAllowedPartitions{
837 "vendor_boot",
838 "vendor_boot_a",
839 "vendor_boot_b",
840 };
841
Yifan Honga4eb4752021-02-16 19:37:21 -0800842 FastbootDevice* device_;
843 const std::vector<std::string>* args_ = nullptr;
844 std::string partition_name_;
845 PartitionHandle handle_;
846 uint64_t partition_size_ = 0;
847 uint64_t start_offset_ = 0;
848 uint64_t total_size_to_read_ = 0;
849
850 // What FetchHandler should return.
851 std::optional<bool> ret_ = std::nullopt;
852};
853} // namespace
854
855bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
856 return PartitionFetcher::Fetch(device, args);
857}