blob: 823783eb2f302ffd7abffd4ec72ef7a06686de7e [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
Kelvin Zhang6befe782022-06-21 14:20:54 -070043#include "BootControlClient.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070044#include "constants.h"
Hridya Valsarajudea91b42018-07-17 11:14:01 -070045#include "fastboot_device.h"
David Anderson12211d12018-07-24 15:21:20 -070046#include "flashing.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070047#include "utility.h"
48
Yifan Honga4eb4752021-02-16 19:37:21 -080049#ifdef FB_ENABLE_FETCH
50static constexpr bool kEnableFetch = true;
51#else
52static constexpr bool kEnableFetch = false;
53#endif
54
David Anderson27475322019-06-11 14:00:08 -070055using android::fs_mgr::MetadataBuilder;
Kelvin Zhang6befe782022-06-21 14:20:54 -070056using android::hal::CommandResult;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070057using ::android::hardware::hidl_string;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070058using ::android::hardware::fastboot::V1_0::Result;
59using ::android::hardware::fastboot::V1_0::Status;
David Anderson220ddb12019-10-31 18:02:41 -070060using android::snapshot::SnapshotManager;
Kelvin Zhang6befe782022-06-21 14:20:54 -070061using MergeStatus = android::hal::BootControlClient::MergeStatus;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070062
Yifan Honga4eb4752021-02-16 19:37:21 -080063using namespace android::storage_literals;
64
David Anderson0f626632018-08-31 16:44:25 -070065struct VariableHandlers {
66 // Callback to retrieve the value of a single variable.
67 std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
68 // Callback to retrieve all possible argument combinations, for getvar all.
69 std::function<std::vector<std::vector<std::string>>(FastbootDevice*)> get_all_args;
70};
71
David Anderson220ddb12019-10-31 18:02:41 -070072static bool IsSnapshotUpdateInProgress(FastbootDevice* device) {
73 auto hal = device->boot1_1();
74 if (!hal) {
75 return false;
76 }
77 auto merge_status = hal->getSnapshotMergeStatus();
78 return merge_status == MergeStatus::SNAPSHOTTED || merge_status == MergeStatus::MERGING;
79}
80
81static bool IsProtectedPartitionDuringMerge(FastbootDevice* device, const std::string& name) {
82 static const std::unordered_set<std::string> ProtectedPartitionsDuringMerge = {
83 "userdata", "metadata", "misc"};
84 if (ProtectedPartitionsDuringMerge.count(name) == 0) {
85 return false;
86 }
87 return IsSnapshotUpdateInProgress(device);
88}
89
David Anderson0f626632018-08-31 16:44:25 -070090static void GetAllVars(FastbootDevice* device, const std::string& name,
91 const VariableHandlers& handlers) {
92 if (!handlers.get_all_args) {
93 std::string message;
94 if (!handlers.get(device, std::vector<std::string>(), &message)) {
95 return;
96 }
97 device->WriteInfo(android::base::StringPrintf("%s:%s", name.c_str(), message.c_str()));
98 return;
99 }
100
101 auto all_args = handlers.get_all_args(device);
102 for (const auto& args : all_args) {
103 std::string message;
104 if (!handlers.get(device, args, &message)) {
105 continue;
106 }
107 std::string arg_string = android::base::Join(args, ":");
108 device->WriteInfo(android::base::StringPrintf("%s:%s:%s", name.c_str(), arg_string.c_str(),
109 message.c_str()));
110 }
111}
112
David Andersonebc8fe12022-06-17 19:17:43 -0700113const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
114 {FB_VAR_VERSION, {GetVersion, nullptr}},
115 {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
116 {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
117 {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
118 {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
119 {FB_VAR_PRODUCT, {GetProduct, nullptr}},
120 {FB_VAR_SERIALNO, {GetSerial, nullptr}},
121 {FB_VAR_VARIANT, {GetVariant, nullptr}},
122 {FB_VAR_SECURE, {GetSecure, nullptr}},
123 {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
124 {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
125 {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
126 {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
127 {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
128 {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
129 {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
130 {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
131 {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
132 {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
133 {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
134 {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
135 {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
136 {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
137 {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
138 {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
139 {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
140 {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
141 {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
142 {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
143 {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
144 {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
145 {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
146 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
147 {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
148};
David Anderson0f626632018-08-31 16:44:25 -0700149
David Andersonebc8fe12022-06-17 19:17:43 -0700150static bool GetVarAll(FastbootDevice* device) {
151 for (const auto& [name, handlers] : kVariableMap) {
152 GetAllVars(device, name, handlers);
153 }
154 return true;
155}
156
157const std::unordered_map<std::string, std::function<bool(FastbootDevice*)>> kSpecialVars = {
158 {"all", GetVarAll},
159 {"dmesg", GetDmesg},
160};
161
162bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson0f626632018-08-31 16:44:25 -0700163 if (args.size() < 2) {
164 return device->WriteFail("Missing argument");
165 }
166
David Andersonebc8fe12022-06-17 19:17:43 -0700167 // "all" and "dmesg" are multiline and handled specially.
168 auto found_special = kSpecialVars.find(args[1]);
169 if (found_special != kSpecialVars.end()) {
170 if (!found_special->second(device)) {
171 return false;
David Anderson0f626632018-08-31 16:44:25 -0700172 }
173 return device->WriteOkay("");
174 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700175
176 // args[0] is command name, args[1] is variable.
177 auto found_variable = kVariableMap.find(args[1]);
178 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700179 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700180 }
181
David Anderson1fb3fd72018-08-31 14:40:22 -0700182 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700183 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700184 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700185 return device->WriteFail(message);
186 }
187 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700188}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700189
josephjang29069752020-09-23 16:28:03 +0800190bool OemPostWipeData(FastbootDevice* device) {
191 auto fastboot_hal = device->fastboot_hal();
192 if (!fastboot_hal) {
193 return false;
194 }
195
196 Result ret;
197 auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
198 if (!ret_val.isOk()) {
199 return false;
200 }
201 if (ret.status == Status::NOT_SUPPORTED) {
202 return false;
203 } else if (ret.status != Status::SUCCESS) {
204 device->WriteStatus(FastbootResult::FAIL, ret.message);
205 } else {
206 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
207 }
208
209 return true;
210}
211
David Anderson12211d12018-07-24 15:21:20 -0700212bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
213 if (args.size() < 2) {
214 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
215 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700216
217 if (GetDeviceLockStatus()) {
218 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
219 }
220
David Anderson220ddb12019-10-31 18:02:41 -0700221 const auto& partition_name = args[1];
222 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
223 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
224 return device->WriteFail(message);
225 }
226
David Anderson12211d12018-07-24 15:21:20 -0700227 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700228 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700229 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
230 }
231 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800232 //Perform oem PostWipeData if Android userdata partition has been erased
233 bool support_oem_postwipedata = false;
234 if (partition_name == "userdata") {
235 support_oem_postwipedata = OemPostWipeData(device);
236 }
237
238 if (!support_oem_postwipedata) {
239 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
240 } else {
241 //Write device status in OemPostWipeData(), so just return true
242 return true;
243 }
David Anderson12211d12018-07-24 15:21:20 -0700244 }
245 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
246}
247
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700248bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
249 auto fastboot_hal = device->fastboot_hal();
250 if (!fastboot_hal) {
251 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
252 }
253
josephjangad90b452020-09-16 16:27:42 +0800254 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
255 if (args[0] == "oem postwipedata userdata") {
256 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
257 }
258
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700259 Result ret;
260 auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
261 if (!ret_val.isOk()) {
262 return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
263 }
264 if (ret.status != Status::SUCCESS) {
265 return device->WriteStatus(FastbootResult::FAIL, ret.message);
266 }
267
Michael Bestasbcf76802022-05-11 22:24:40 +0300268 device->WriteInfo(ret.message);
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700269 return device->WriteStatus(FastbootResult::OKAY, ret.message);
270}
271
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700272bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
273 if (args.size() < 2) {
274 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
275 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700276
277 if (GetDeviceLockStatus()) {
278 return device->WriteStatus(FastbootResult::FAIL,
279 "Download is not allowed on locked devices");
280 }
281
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700282 // arg[0] is the command name, arg[1] contains size of data to be downloaded
Keith Mok3724bbc2021-12-30 20:08:04 +0000283 // which should always be 8 bytes
284 if (args[1].length() != 8) {
285 return device->WriteStatus(FastbootResult::FAIL,
286 "Invalid size (length of size != 8)");
287 }
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700288 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700289 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700290 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
291 }
Keith Mok3724bbc2021-12-30 20:08:04 +0000292 if (size == 0) {
293 return device->WriteStatus(FastbootResult::FAIL, "Invalid size (0)");
294 }
David Anderson12211d12018-07-24 15:21:20 -0700295 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700296 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
297 return false;
298 }
299
David Anderson12211d12018-07-24 15:21:20 -0700300 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700301 return device->WriteStatus(FastbootResult::OKAY, "");
302 }
303
304 PLOG(ERROR) << "Couldn't download data";
305 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
306}
307
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700308bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
309 if (args.size() < 2) {
310 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
311 }
312
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700313 if (GetDeviceLockStatus()) {
314 return device->WriteStatus(FastbootResult::FAIL,
315 "set_active command is not allowed on locked devices");
316 }
317
Kelvin Zhang6befe782022-06-21 14:20:54 -0700318 int32_t slot = 0;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700319 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700320 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700321 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
322 }
323
324 // Non-A/B devices will not have a boot control HAL.
325 auto boot_control_hal = device->boot_control_hal();
326 if (!boot_control_hal) {
327 return device->WriteStatus(FastbootResult::FAIL,
328 "Cannot set slot: boot control HAL absent");
329 }
Kelvin Zhang6befe782022-06-21 14:20:54 -0700330 if (slot >= boot_control_hal->GetNumSlots()) {
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700331 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
332 }
David Anderson220ddb12019-10-31 18:02:41 -0700333
334 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800335 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700336 return device->WriteOkay("");
337 }
338
339 // Check how to handle the current snapshot state.
340 if (auto hal11 = device->boot1_1()) {
341 auto merge_status = hal11->getSnapshotMergeStatus();
342 if (merge_status == MergeStatus::MERGING) {
343 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
344 }
345 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
346 // stage init does not have access to the HAL, and uses the slot number
347 // and /metadata OTA state to determine whether a slot change occurred.
348 // Booting into the old slot would erase the OTA, and switching A->B->A
349 // would simply resume it if no boots occur in between. Re-flashing
350 // partitions implicitly cancels the OTA, so leaving the state as-is is
351 // safe.
352 if (merge_status == MergeStatus::SNAPSHOTTED) {
353 device->WriteInfo(
354 "Changing the active slot with a snapshot applied may cancel the"
355 " update.");
356 }
357 }
358
Kelvin Zhang6befe782022-06-21 14:20:54 -0700359 CommandResult ret = boot_control_hal->SetActiveBootSlot(slot);
360 if (ret.success) {
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700361 // Save as slot suffix to match the suffix format as returned from
362 // the boot control HAL.
363 auto current_slot = "_" + args[1];
364 device->set_active_slot(current_slot);
365 return device->WriteStatus(FastbootResult::OKAY, "");
366 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700367 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700368}
369
370bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
371 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
372 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
373 device->CloseDevice();
374 TEMP_FAILURE_RETRY(pause());
375 return result;
376}
377
378bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
379 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
380 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
381 device->CloseDevice();
382 TEMP_FAILURE_RETRY(pause());
383 return result;
384}
385
386bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
387 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
388 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
389 device->CloseDevice();
390 TEMP_FAILURE_RETRY(pause());
391 return result;
392}
393
394bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
395 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
396 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
397 device->CloseDevice();
398 TEMP_FAILURE_RETRY(pause());
399 return result;
400}
401
402static bool EnterRecovery() {
403 const char msg_switch_to_recovery = 'r';
404
405 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
406 if (sock < 0) {
407 PLOG(ERROR) << "Couldn't create sock";
408 return false;
409 }
410
411 struct sockaddr_un addr = {.sun_family = AF_UNIX};
412 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
Yifan Hong07e947f2021-03-22 19:21:34 -0700413 if (connect(sock.get(), (struct sockaddr*)&addr, sizeof(addr)) < 0) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700414 PLOG(ERROR) << "Couldn't connect to recovery";
415 return false;
416 }
417 // Switch to recovery will not update the boot reason since it does not
418 // require a reboot.
Yifan Hong07e947f2021-03-22 19:21:34 -0700419 auto ret = write(sock.get(), &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700420 if (ret != sizeof(msg_switch_to_recovery)) {
421 PLOG(ERROR) << "Couldn't write message to switch to recovery";
422 return false;
423 }
424
425 return true;
426}
427
428bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
429 auto status = true;
430 if (EnterRecovery()) {
431 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
432 } else {
433 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
434 }
435 device->CloseDevice();
436 TEMP_FAILURE_RETRY(pause());
437 return status;
438}
David Anderson0d4277d2018-07-31 13:27:37 -0700439
440// Helper class for opening a handle to a MetadataBuilder and writing the new
441// partition table to the same place it was read.
442class PartitionBuilder {
443 public:
David Andersond25f1c32018-11-09 20:41:33 -0800444 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700445
446 bool Write();
447 bool Valid() const { return !!builder_; }
448 MetadataBuilder* operator->() const { return builder_.get(); }
449
450 private:
David Anderson4d307b02018-12-17 17:07:34 -0800451 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700452 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800453 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700454 std::unique_ptr<MetadataBuilder> builder_;
455};
456
David Anderson4d307b02018-12-17 17:07:34 -0800457PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
458 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800459 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700460 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800461 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700462 if (!super_device) {
463 return;
464 }
465 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800466 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700467}
468
469bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700470 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700471 if (!metadata) {
472 return false;
473 }
David Anderson4d307b02018-12-17 17:07:34 -0800474 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700475}
476
477bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
478 if (args.size() < 3) {
479 return device->WriteFail("Invalid partition name and size");
480 }
481
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700482 if (GetDeviceLockStatus()) {
483 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
484 }
485
David Anderson0d4277d2018-07-31 13:27:37 -0700486 uint64_t partition_size;
487 std::string partition_name = args[1];
488 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
489 return device->WriteFail("Invalid partition size");
490 }
491
David Andersond25f1c32018-11-09 20:41:33 -0800492 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700493 if (!builder.Valid()) {
494 return device->WriteFail("Could not open super partition");
495 }
496 // TODO(112433293) Disallow if the name is in the physical table as well.
497 if (builder->FindPartition(partition_name)) {
498 return device->WriteFail("Partition already exists");
499 }
500
David Anderson27475322019-06-11 14:00:08 -0700501 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700502 if (!partition) {
503 return device->WriteFail("Failed to add partition");
504 }
505 if (!builder->ResizePartition(partition, partition_size)) {
506 builder->RemovePartition(partition_name);
507 return device->WriteFail("Not enough space for partition");
508 }
509 if (!builder.Write()) {
510 return device->WriteFail("Failed to write partition table");
511 }
512 return device->WriteOkay("Partition created");
513}
514
515bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
516 if (args.size() < 2) {
517 return device->WriteFail("Invalid partition name and size");
518 }
519
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700520 if (GetDeviceLockStatus()) {
521 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
522 }
523
David Andersond25f1c32018-11-09 20:41:33 -0800524 std::string partition_name = args[1];
525
526 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700527 if (!builder.Valid()) {
528 return device->WriteFail("Could not open super partition");
529 }
David Andersond25f1c32018-11-09 20:41:33 -0800530 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700531 if (!builder.Write()) {
532 return device->WriteFail("Failed to write partition table");
533 }
534 return device->WriteOkay("Partition deleted");
535}
536
537bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
538 if (args.size() < 3) {
539 return device->WriteFail("Invalid partition name and size");
540 }
541
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700542 if (GetDeviceLockStatus()) {
543 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
544 }
545
David Anderson0d4277d2018-07-31 13:27:37 -0700546 uint64_t partition_size;
547 std::string partition_name = args[1];
548 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
549 return device->WriteFail("Invalid partition size");
550 }
551
David Andersond25f1c32018-11-09 20:41:33 -0800552 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700553 if (!builder.Valid()) {
554 return device->WriteFail("Could not open super partition");
555 }
556
David Anderson27475322019-06-11 14:00:08 -0700557 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700558 if (!partition) {
559 return device->WriteFail("Partition does not exist");
560 }
David Andersonad970fc2019-08-27 14:01:16 -0700561
562 // Remove the updated flag to cancel any snapshots.
563 uint32_t attrs = partition->attributes();
564 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
565
David Anderson0d4277d2018-07-31 13:27:37 -0700566 if (!builder->ResizePartition(partition, partition_size)) {
567 return device->WriteFail("Not enough space to resize partition");
568 }
569 if (!builder.Write()) {
570 return device->WriteFail("Failed to write partition table");
571 }
572 return device->WriteOkay("Partition resized");
573}
David Anderson38b3c7a2018-08-15 16:27:42 -0700574
David Andersonad970fc2019-08-27 14:01:16 -0700575void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
576 PartitionBuilder builder(device, partition_name);
577 if (!builder.Valid()) return;
578
579 auto partition = builder->FindPartition(partition_name);
580 if (!partition) return;
581
582 // Remove the updated flag to cancel any snapshots.
583 uint32_t attrs = partition->attributes();
584 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
585
586 builder.Write();
587}
588
589bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
590 if (args.size() < 2) {
591 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
592 }
593
594 if (GetDeviceLockStatus()) {
595 return device->WriteStatus(FastbootResult::FAIL,
596 "Flashing is not allowed on locked devices");
597 }
598
599 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700600 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
601 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
602 return device->WriteFail(message);
603 }
604
David Andersonad970fc2019-08-27 14:01:16 -0700605 if (LogicalPartitionExists(device, partition_name)) {
606 CancelPartitionSnapshot(device, partition_name);
607 }
608
609 int ret = Flash(device, partition_name);
610 if (ret < 0) {
611 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
612 }
613 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
614}
615
David Anderson38b3c7a2018-08-15 16:27:42 -0700616bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
617 if (args.size() < 2) {
618 return device->WriteFail("Invalid arguments");
619 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700620
621 if (GetDeviceLockStatus()) {
622 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
623 }
624
David Anderson38b3c7a2018-08-15 16:27:42 -0700625 bool wipe = (args.size() >= 3 && args[2] == "wipe");
626 return UpdateSuper(device, args[1], wipe);
627}
David Anderson1d504e32019-01-15 14:38:20 -0800628
David Anderson3d782d52019-01-29 13:09:49 -0800629bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800630 if (args.size() != 2) {
631 return device->WriteFail("Invalid arguments");
632 }
David Anderson3d782d52019-01-29 13:09:49 -0800633
634 AutoMountMetadata mount_metadata;
635 if (!mount_metadata) {
636 return device->WriteFail("Could not find GSI install");
637 }
638
639 if (!android::gsi::IsGsiInstalled()) {
640 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
641 }
642
David Anderson1d504e32019-01-15 14:38:20 -0800643 if (args[1] == "wipe") {
644 if (!android::gsi::UninstallGsi()) {
645 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
646 }
647 } else if (args[1] == "disable") {
648 if (!android::gsi::DisableGsi()) {
649 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
650 }
651 }
652 return device->WriteStatus(FastbootResult::OKAY, "Success");
653}
David Andersonab8f4662019-10-21 16:45:59 -0700654
655bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
656 // Note that we use the HAL rather than mounting /metadata, since we want
657 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700658 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700659 if (!hal) return device->WriteFail("Not supported");
660
David Andersonab8f4662019-10-21 16:45:59 -0700661 // If no arguments, return the same thing as a getvar. Note that we get the
662 // HAL first so we can return "not supported" before we return the less
663 // specific error message below.
664 if (args.size() < 2 || args[1].empty()) {
665 std::string message;
666 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
667 return device->WriteFail("Could not determine update status");
668 }
669 device->WriteInfo(message);
670 return device->WriteOkay("");
671 }
672
David Anderson220ddb12019-10-31 18:02:41 -0700673 MergeStatus status = hal->getSnapshotMergeStatus();
674
675 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700676 return device->WriteFail("Invalid arguments");
677 }
David Anderson220ddb12019-10-31 18:02:41 -0700678 if (args[1] == "cancel") {
679 switch (status) {
680 case MergeStatus::SNAPSHOTTED:
Kelvin Zhang6befe782022-06-21 14:20:54 -0700681 case MergeStatus::MERGING: {
682 const auto ret = hal->SetSnapshotMergeStatus(MergeStatus::CANCELLED);
683 if (!ret.success) {
684 device->WriteFail("Failed to SetSnapshotMergeStatus(MergeStatus::CANCELLED) " +
685 ret.errMsg);
686 }
David Anderson220ddb12019-10-31 18:02:41 -0700687 break;
Kelvin Zhang6befe782022-06-21 14:20:54 -0700688 }
David Anderson220ddb12019-10-31 18:02:41 -0700689 default:
690 break;
691 }
692 } else if (args[1] == "merge") {
693 if (status != MergeStatus::MERGING) {
694 return device->WriteFail("No snapshot merge is in progress");
695 }
David Andersonab8f4662019-10-21 16:45:59 -0700696
David Anderson565577f2021-02-04 20:14:18 -0800697 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700698 if (!sm) {
699 return device->WriteFail("Unable to create SnapshotManager");
700 }
David Anderson5a0177d2020-04-30 18:53:23 -0700701 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700702 return device->WriteFail("Unable to finish snapshot merge");
703 }
704 } else {
705 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700706 }
707 return device->WriteStatus(FastbootResult::OKAY, "Success");
708}
Yifan Honga4eb4752021-02-16 19:37:21 -0800709
710namespace {
711// Helper of FetchHandler.
712class PartitionFetcher {
713 public:
714 static bool Fetch(FastbootDevice* device, const std::vector<std::string>& args) {
715 if constexpr (!kEnableFetch) {
716 return device->WriteFail("Fetch is not allowed on user build");
717 }
718
719 if (GetDeviceLockStatus()) {
720 return device->WriteFail("Fetch is not allowed on locked devices");
721 }
722
723 PartitionFetcher fetcher(device, args);
724 if (fetcher.Open()) {
725 fetcher.Fetch();
726 }
727 CHECK(fetcher.ret_.has_value());
728 return *fetcher.ret_;
729 }
730
731 private:
732 PartitionFetcher(FastbootDevice* device, const std::vector<std::string>& args)
733 : device_(device), args_(&args) {}
734 // Return whether the partition is successfully opened.
735 // If successfully opened, ret_ is left untouched. Otherwise, ret_ is set to the value
736 // that FetchHandler should return.
737 bool Open() {
Yifan Hongbcd27702021-02-16 19:37:32 -0800738 if (args_->size() < 2) {
739 ret_ = device_->WriteFail("Missing partition arg");
Yifan Honga4eb4752021-02-16 19:37:21 -0800740 return false;
741 }
742
Yifan Hongbcd27702021-02-16 19:37:32 -0800743 partition_name_ = args_->at(1);
744 if (std::find(kAllowedPartitions.begin(), kAllowedPartitions.end(), partition_name_) ==
745 kAllowedPartitions.end()) {
746 ret_ = device_->WriteFail("Fetch is only allowed on [" +
747 android::base::Join(kAllowedPartitions, ", ") + "]");
748 return false;
749 }
750
Konstantin Vyshetsky81cc1192021-11-04 10:27:06 -0700751 if (!OpenPartition(device_, partition_name_, &handle_, O_RDONLY)) {
Yifan Honga4eb4752021-02-16 19:37:21 -0800752 ret_ = device_->WriteFail(
753 android::base::StringPrintf("Cannot open %s", partition_name_.c_str()));
754 return false;
755 }
756
757 partition_size_ = get_block_device_size(handle_.fd());
758 if (partition_size_ == 0) {
759 ret_ = device_->WriteOkay(android::base::StringPrintf("Partition %s has size 0",
760 partition_name_.c_str()));
761 return false;
762 }
763
764 start_offset_ = 0;
765 if (args_->size() >= 3) {
766 if (!android::base::ParseUint(args_->at(2), &start_offset_)) {
767 ret_ = device_->WriteFail("Invalid offset, must be integer");
768 return false;
769 }
770 if (start_offset_ > std::numeric_limits<off64_t>::max()) {
771 ret_ = device_->WriteFail(
772 android::base::StringPrintf("Offset overflows: %" PRIx64, start_offset_));
773 return false;
774 }
775 }
776 if (start_offset_ > partition_size_) {
777 ret_ = device_->WriteFail(android::base::StringPrintf(
778 "Invalid offset 0x%" PRIx64 ", partition %s has size 0x%" PRIx64, start_offset_,
779 partition_name_.c_str(), partition_size_));
780 return false;
781 }
782 uint64_t maximum_total_size_to_read = partition_size_ - start_offset_;
783 total_size_to_read_ = maximum_total_size_to_read;
784 if (args_->size() >= 4) {
785 if (!android::base::ParseUint(args_->at(3), &total_size_to_read_)) {
786 ret_ = device_->WriteStatus(FastbootResult::FAIL, "Invalid size, must be integer");
787 return false;
788 }
789 }
790 if (total_size_to_read_ == 0) {
791 ret_ = device_->WriteOkay("Read 0 bytes");
792 return false;
793 }
794 if (total_size_to_read_ > maximum_total_size_to_read) {
795 ret_ = device_->WriteFail(android::base::StringPrintf(
796 "Invalid size to read 0x%" PRIx64 ", partition %s has size 0x%" PRIx64
797 " and fetching from offset 0x%" PRIx64,
798 total_size_to_read_, partition_name_.c_str(), partition_size_, start_offset_));
799 return false;
800 }
801
802 if (total_size_to_read_ > kMaxFetchSizeDefault) {
803 ret_ = device_->WriteFail(android::base::StringPrintf(
804 "Cannot fetch 0x%" PRIx64
805 " bytes because it exceeds maximum transport size 0x%x",
806 partition_size_, kMaxDownloadSizeDefault));
807 return false;
808 }
809
810 return true;
811 }
812
813 // Assume Open() returns true.
814 // After execution, ret_ is set to the value that FetchHandler should return.
815 void Fetch() {
816 CHECK(start_offset_ <= std::numeric_limits<off64_t>::max());
817 if (lseek64(handle_.fd(), start_offset_, SEEK_SET) != static_cast<off64_t>(start_offset_)) {
818 ret_ = device_->WriteFail(android::base::StringPrintf(
819 "On partition %s, unable to lseek(0x%" PRIx64 ": %s", partition_name_.c_str(),
820 start_offset_, strerror(errno)));
821 return;
822 }
823
824 if (!device_->WriteStatus(FastbootResult::DATA,
825 android::base::StringPrintf(
826 "%08x", static_cast<uint32_t>(total_size_to_read_)))) {
827 ret_ = false;
828 return;
829 }
830 uint64_t end_offset = start_offset_ + total_size_to_read_;
831 std::vector<char> buf(1_MiB);
832 uint64_t current_offset = start_offset_;
833 while (current_offset < end_offset) {
834 // On any error, exit. We can't return a status message to the driver because
835 // we are in the middle of writing data, so just let the driver guess what's wrong
836 // by ending the data stream prematurely.
837 uint64_t remaining = end_offset - current_offset;
838 uint64_t chunk_size = std::min<uint64_t>(buf.size(), remaining);
839 if (!android::base::ReadFully(handle_.fd(), buf.data(), chunk_size)) {
840 PLOG(ERROR) << std::hex << "Unable to read 0x" << chunk_size << " bytes from "
841 << partition_name_ << " @ offset 0x" << current_offset;
842 ret_ = false;
843 return;
844 }
845 if (!device_->HandleData(false /* is read */, buf.data(), chunk_size)) {
846 PLOG(ERROR) << std::hex << "Unable to send 0x" << chunk_size << " bytes of "
847 << partition_name_ << " @ offset 0x" << current_offset;
848 ret_ = false;
849 return;
850 }
851 current_offset += chunk_size;
852 }
853
854 ret_ = device_->WriteOkay(android::base::StringPrintf(
855 "Fetched %s (offset=0x%" PRIx64 ", size=0x%" PRIx64, partition_name_.c_str(),
856 start_offset_, total_size_to_read_));
857 }
858
Yifan Hongbcd27702021-02-16 19:37:32 -0800859 static constexpr std::array<const char*, 3> kAllowedPartitions{
860 "vendor_boot",
861 "vendor_boot_a",
862 "vendor_boot_b",
863 };
864
Yifan Honga4eb4752021-02-16 19:37:21 -0800865 FastbootDevice* device_;
866 const std::vector<std::string>* args_ = nullptr;
867 std::string partition_name_;
868 PartitionHandle handle_;
869 uint64_t partition_size_ = 0;
870 uint64_t start_offset_ = 0;
871 uint64_t total_size_to_read_ = 0;
872
873 // What FetchHandler should return.
874 std::optional<bool> ret_ = std::nullopt;
875};
876} // namespace
877
878bool FetchHandler(FastbootDevice* device, const std::vector<std::string>& args) {
879 return PartitionFetcher::Fetch(device, args);
880}