blob: 3c56f50017e9907a3b71c20183cd7c2f42240a4c [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
19#include <sys/socket.h>
20#include <sys/un.h>
21
David Anderson220ddb12019-10-31 18:02:41 -070022#include <unordered_set>
23
Hridya Valsarajudea91b42018-07-17 11:14:01 -070024#include <android-base/logging.h>
25#include <android-base/parseint.h>
26#include <android-base/properties.h>
27#include <android-base/stringprintf.h>
28#include <android-base/strings.h>
29#include <android-base/unique_fd.h>
David Andersonab8f4662019-10-21 16:45:59 -070030#include <android/hardware/boot/1.1/IBootControl.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070031#include <cutils/android_reboot.h>
David Anderson12211d12018-07-24 15:21:20 -070032#include <ext4_utils/wipe.h>
David Anderson5cbd2e42018-09-27 10:53:04 -070033#include <fs_mgr.h>
David Anderson2ffc31b2020-03-23 23:43:45 -070034#include <fs_mgr/roots.h>
David Anderson1d504e32019-01-15 14:38:20 -080035#include <libgsi/libgsi.h>
David Anderson0d4277d2018-07-31 13:27:37 -070036#include <liblp/builder.h>
37#include <liblp/liblp.h>
David Anderson220ddb12019-10-31 18:02:41 -070038#include <libsnapshot/snapshot.h>
David Anderson0d4277d2018-07-31 13:27:37 -070039#include <uuid/uuid.h>
Hridya Valsarajudea91b42018-07-17 11:14:01 -070040
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070041#include "constants.h"
Hridya Valsarajudea91b42018-07-17 11:14:01 -070042#include "fastboot_device.h"
David Anderson12211d12018-07-24 15:21:20 -070043#include "flashing.h"
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070044#include "utility.h"
45
David Anderson27475322019-06-11 14:00:08 -070046using android::fs_mgr::MetadataBuilder;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -070047using ::android::hardware::hidl_string;
48using ::android::hardware::boot::V1_0::BoolResult;
49using ::android::hardware::boot::V1_0::CommandResult;
50using ::android::hardware::boot::V1_0::Slot;
David Andersonab8f4662019-10-21 16:45:59 -070051using ::android::hardware::boot::V1_1::MergeStatus;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070052using ::android::hardware::fastboot::V1_0::Result;
53using ::android::hardware::fastboot::V1_0::Status;
David Anderson220ddb12019-10-31 18:02:41 -070054using android::snapshot::SnapshotManager;
David Andersonab8f4662019-10-21 16:45:59 -070055using IBootControl1_1 = ::android::hardware::boot::V1_1::IBootControl;
Hridya Valsarajua15fe312018-09-14 13:58:21 -070056
David Anderson0f626632018-08-31 16:44:25 -070057struct VariableHandlers {
58 // Callback to retrieve the value of a single variable.
59 std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
60 // Callback to retrieve all possible argument combinations, for getvar all.
61 std::function<std::vector<std::vector<std::string>>(FastbootDevice*)> get_all_args;
62};
63
David Anderson220ddb12019-10-31 18:02:41 -070064static bool IsSnapshotUpdateInProgress(FastbootDevice* device) {
65 auto hal = device->boot1_1();
66 if (!hal) {
67 return false;
68 }
69 auto merge_status = hal->getSnapshotMergeStatus();
70 return merge_status == MergeStatus::SNAPSHOTTED || merge_status == MergeStatus::MERGING;
71}
72
73static bool IsProtectedPartitionDuringMerge(FastbootDevice* device, const std::string& name) {
74 static const std::unordered_set<std::string> ProtectedPartitionsDuringMerge = {
75 "userdata", "metadata", "misc"};
76 if (ProtectedPartitionsDuringMerge.count(name) == 0) {
77 return false;
78 }
79 return IsSnapshotUpdateInProgress(device);
80}
81
David Anderson0f626632018-08-31 16:44:25 -070082static void GetAllVars(FastbootDevice* device, const std::string& name,
83 const VariableHandlers& handlers) {
84 if (!handlers.get_all_args) {
85 std::string message;
86 if (!handlers.get(device, std::vector<std::string>(), &message)) {
87 return;
88 }
89 device->WriteInfo(android::base::StringPrintf("%s:%s", name.c_str(), message.c_str()));
90 return;
91 }
92
93 auto all_args = handlers.get_all_args(device);
94 for (const auto& args : all_args) {
95 std::string message;
96 if (!handlers.get(device, args, &message)) {
97 continue;
98 }
99 std::string arg_string = android::base::Join(args, ":");
100 device->WriteInfo(android::base::StringPrintf("%s:%s:%s", name.c_str(), arg_string.c_str(),
101 message.c_str()));
102 }
103}
104
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700105bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson0f626632018-08-31 16:44:25 -0700106 const std::unordered_map<std::string, VariableHandlers> kVariableMap = {
107 {FB_VAR_VERSION, {GetVersion, nullptr}},
108 {FB_VAR_VERSION_BOOTLOADER, {GetBootloaderVersion, nullptr}},
109 {FB_VAR_VERSION_BASEBAND, {GetBasebandVersion, nullptr}},
Bowgo Tsai99f9a382020-01-21 18:31:23 +0800110 {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
111 {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
David Anderson0f626632018-08-31 16:44:25 -0700112 {FB_VAR_PRODUCT, {GetProduct, nullptr}},
113 {FB_VAR_SERIALNO, {GetSerial, nullptr}},
Hridya Valsaraju4af80902018-09-26 13:08:16 -0700114 {FB_VAR_VARIANT, {GetVariant, nullptr}},
David Anderson0f626632018-08-31 16:44:25 -0700115 {FB_VAR_SECURE, {GetSecure, nullptr}},
116 {FB_VAR_UNLOCKED, {GetUnlocked, nullptr}},
117 {FB_VAR_MAX_DOWNLOAD_SIZE, {GetMaxDownloadSize, nullptr}},
118 {FB_VAR_CURRENT_SLOT, {::GetCurrentSlot, nullptr}},
119 {FB_VAR_SLOT_COUNT, {GetSlotCount, nullptr}},
120 {FB_VAR_HAS_SLOT, {GetHasSlot, GetAllPartitionArgsNoSlot}},
121 {FB_VAR_SLOT_SUCCESSFUL, {GetSlotSuccessful, nullptr}},
122 {FB_VAR_SLOT_UNBOOTABLE, {GetSlotUnbootable, nullptr}},
David Anderson27475322019-06-11 14:00:08 -0700123 {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
Hridya Valsarajubf9f8d12018-09-05 16:57:24 -0700124 {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
David Anderson0f626632018-08-31 16:44:25 -0700125 {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
David Andersonc091c172018-09-04 18:11:03 -0700126 {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
Hridya Valsaraju7c9bbe92018-09-27 10:41:01 -0700127 {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
Hridya Valsaraju47658ca2018-09-28 11:41:22 -0700128 {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
Hridya Valsarajua534a5a2018-10-03 15:53:22 -0700129 {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
David Anderson90fe0a42018-11-05 18:01:32 -0800130 {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
David Andersonab8f4662019-10-21 16:45:59 -0700131 {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
Bowgo Tsai33da5c92019-11-13 17:13:49 +0800132 {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
Bowgo Tsai99f9a382020-01-21 18:31:23 +0800133 {FB_VAR_CPU_ABI, {GetCpuAbi, nullptr}},
134 {FB_VAR_SYSTEM_FINGERPRINT, {GetSystemFingerprint, nullptr}},
135 {FB_VAR_VENDOR_FINGERPRINT, {GetVendorFingerprint, nullptr}},
136 {FB_VAR_DYNAMIC_PARTITION, {GetDynamicPartition, nullptr}},
137 {FB_VAR_FIRST_API_LEVEL, {GetFirstApiLevel, nullptr}},
138 {FB_VAR_SECURITY_PATCH_LEVEL, {GetSecurityPatchLevel, nullptr}},
Yifan Hongb299cb72021-02-17 13:44:49 -0800139 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}},
140 {FB_VAR_MAX_FETCH_SIZE, {GetMaxFetchSize, nullptr}},
141 };
David Anderson0f626632018-08-31 16:44:25 -0700142
143 if (args.size() < 2) {
144 return device->WriteFail("Missing argument");
145 }
146
147 // Special case: return all variables that we can.
148 if (args[1] == "all") {
149 for (const auto& [name, handlers] : kVariableMap) {
150 GetAllVars(device, name, handlers);
151 }
152 return device->WriteOkay("");
153 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700154
155 // args[0] is command name, args[1] is variable.
156 auto found_variable = kVariableMap.find(args[1]);
157 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700158 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700159 }
160
David Anderson1fb3fd72018-08-31 14:40:22 -0700161 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700162 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700163 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700164 return device->WriteFail(message);
165 }
166 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700167}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700168
josephjang29069752020-09-23 16:28:03 +0800169bool OemPostWipeData(FastbootDevice* device) {
170 auto fastboot_hal = device->fastboot_hal();
171 if (!fastboot_hal) {
172 return false;
173 }
174
175 Result ret;
176 auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
177 if (!ret_val.isOk()) {
178 return false;
179 }
180 if (ret.status == Status::NOT_SUPPORTED) {
181 return false;
182 } else if (ret.status != Status::SUCCESS) {
183 device->WriteStatus(FastbootResult::FAIL, ret.message);
184 } else {
185 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
186 }
187
188 return true;
189}
190
David Anderson12211d12018-07-24 15:21:20 -0700191bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
192 if (args.size() < 2) {
193 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
194 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700195
196 if (GetDeviceLockStatus()) {
197 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
198 }
199
David Anderson220ddb12019-10-31 18:02:41 -0700200 const auto& partition_name = args[1];
201 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
202 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
203 return device->WriteFail(message);
204 }
205
David Anderson12211d12018-07-24 15:21:20 -0700206 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700207 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700208 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
209 }
210 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800211 //Perform oem PostWipeData if Android userdata partition has been erased
212 bool support_oem_postwipedata = false;
213 if (partition_name == "userdata") {
214 support_oem_postwipedata = OemPostWipeData(device);
215 }
216
217 if (!support_oem_postwipedata) {
218 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
219 } else {
220 //Write device status in OemPostWipeData(), so just return true
221 return true;
222 }
David Anderson12211d12018-07-24 15:21:20 -0700223 }
224 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
225}
226
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700227bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
228 auto fastboot_hal = device->fastboot_hal();
229 if (!fastboot_hal) {
230 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
231 }
232
josephjangad90b452020-09-16 16:27:42 +0800233 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
234 if (args[0] == "oem postwipedata userdata") {
235 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
236 }
237
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700238 Result ret;
239 auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
240 if (!ret_val.isOk()) {
241 return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
242 }
243 if (ret.status != Status::SUCCESS) {
244 return device->WriteStatus(FastbootResult::FAIL, ret.message);
245 }
246
247 return device->WriteStatus(FastbootResult::OKAY, ret.message);
248}
249
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700250bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
251 if (args.size() < 2) {
252 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
253 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700254
255 if (GetDeviceLockStatus()) {
256 return device->WriteStatus(FastbootResult::FAIL,
257 "Download is not allowed on locked devices");
258 }
259
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700260 // arg[0] is the command name, arg[1] contains size of data to be downloaded
261 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700262 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700263 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
264 }
David Anderson12211d12018-07-24 15:21:20 -0700265 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700266 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
267 return false;
268 }
269
David Anderson12211d12018-07-24 15:21:20 -0700270 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700271 return device->WriteStatus(FastbootResult::OKAY, "");
272 }
273
274 PLOG(ERROR) << "Couldn't download data";
275 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
276}
277
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700278bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
279 if (args.size() < 2) {
280 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
281 }
282
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700283 if (GetDeviceLockStatus()) {
284 return device->WriteStatus(FastbootResult::FAIL,
285 "set_active command is not allowed on locked devices");
286 }
287
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700288 Slot slot;
289 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700290 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700291 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
292 }
293
294 // Non-A/B devices will not have a boot control HAL.
295 auto boot_control_hal = device->boot_control_hal();
296 if (!boot_control_hal) {
297 return device->WriteStatus(FastbootResult::FAIL,
298 "Cannot set slot: boot control HAL absent");
299 }
300 if (slot >= boot_control_hal->getNumberSlots()) {
301 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
302 }
David Anderson220ddb12019-10-31 18:02:41 -0700303
304 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800305 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700306 return device->WriteOkay("");
307 }
308
309 // Check how to handle the current snapshot state.
310 if (auto hal11 = device->boot1_1()) {
311 auto merge_status = hal11->getSnapshotMergeStatus();
312 if (merge_status == MergeStatus::MERGING) {
313 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
314 }
315 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
316 // stage init does not have access to the HAL, and uses the slot number
317 // and /metadata OTA state to determine whether a slot change occurred.
318 // Booting into the old slot would erase the OTA, and switching A->B->A
319 // would simply resume it if no boots occur in between. Re-flashing
320 // partitions implicitly cancels the OTA, so leaving the state as-is is
321 // safe.
322 if (merge_status == MergeStatus::SNAPSHOTTED) {
323 device->WriteInfo(
324 "Changing the active slot with a snapshot applied may cancel the"
325 " update.");
326 }
327 }
328
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700329 CommandResult ret;
330 auto cb = [&ret](CommandResult result) { ret = result; };
331 auto result = boot_control_hal->setActiveBootSlot(slot, cb);
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700332 if (result.isOk() && ret.success) {
333 // Save as slot suffix to match the suffix format as returned from
334 // the boot control HAL.
335 auto current_slot = "_" + args[1];
336 device->set_active_slot(current_slot);
337 return device->WriteStatus(FastbootResult::OKAY, "");
338 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700339 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700340}
341
342bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
343 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
344 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
345 device->CloseDevice();
346 TEMP_FAILURE_RETRY(pause());
347 return result;
348}
349
350bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
351 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
352 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
353 device->CloseDevice();
354 TEMP_FAILURE_RETRY(pause());
355 return result;
356}
357
358bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
359 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
360 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
361 device->CloseDevice();
362 TEMP_FAILURE_RETRY(pause());
363 return result;
364}
365
366bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
367 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
368 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
369 device->CloseDevice();
370 TEMP_FAILURE_RETRY(pause());
371 return result;
372}
373
374static bool EnterRecovery() {
375 const char msg_switch_to_recovery = 'r';
376
377 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
378 if (sock < 0) {
379 PLOG(ERROR) << "Couldn't create sock";
380 return false;
381 }
382
383 struct sockaddr_un addr = {.sun_family = AF_UNIX};
384 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
385 if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
386 PLOG(ERROR) << "Couldn't connect to recovery";
387 return false;
388 }
389 // Switch to recovery will not update the boot reason since it does not
390 // require a reboot.
391 auto ret = write(sock, &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
392 if (ret != sizeof(msg_switch_to_recovery)) {
393 PLOG(ERROR) << "Couldn't write message to switch to recovery";
394 return false;
395 }
396
397 return true;
398}
399
400bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
401 auto status = true;
402 if (EnterRecovery()) {
403 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
404 } else {
405 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
406 }
407 device->CloseDevice();
408 TEMP_FAILURE_RETRY(pause());
409 return status;
410}
David Anderson0d4277d2018-07-31 13:27:37 -0700411
412// Helper class for opening a handle to a MetadataBuilder and writing the new
413// partition table to the same place it was read.
414class PartitionBuilder {
415 public:
David Andersond25f1c32018-11-09 20:41:33 -0800416 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700417
418 bool Write();
419 bool Valid() const { return !!builder_; }
420 MetadataBuilder* operator->() const { return builder_.get(); }
421
422 private:
David Anderson4d307b02018-12-17 17:07:34 -0800423 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700424 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800425 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700426 std::unique_ptr<MetadataBuilder> builder_;
427};
428
David Anderson4d307b02018-12-17 17:07:34 -0800429PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
430 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800431 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700432 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800433 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700434 if (!super_device) {
435 return;
436 }
437 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800438 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700439}
440
441bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700442 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700443 if (!metadata) {
444 return false;
445 }
David Anderson4d307b02018-12-17 17:07:34 -0800446 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700447}
448
449bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
450 if (args.size() < 3) {
451 return device->WriteFail("Invalid partition name and size");
452 }
453
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700454 if (GetDeviceLockStatus()) {
455 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
456 }
457
David Anderson0d4277d2018-07-31 13:27:37 -0700458 uint64_t partition_size;
459 std::string partition_name = args[1];
460 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
461 return device->WriteFail("Invalid partition size");
462 }
463
David Andersond25f1c32018-11-09 20:41:33 -0800464 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700465 if (!builder.Valid()) {
466 return device->WriteFail("Could not open super partition");
467 }
468 // TODO(112433293) Disallow if the name is in the physical table as well.
469 if (builder->FindPartition(partition_name)) {
470 return device->WriteFail("Partition already exists");
471 }
472
David Anderson27475322019-06-11 14:00:08 -0700473 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700474 if (!partition) {
475 return device->WriteFail("Failed to add partition");
476 }
477 if (!builder->ResizePartition(partition, partition_size)) {
478 builder->RemovePartition(partition_name);
479 return device->WriteFail("Not enough space for partition");
480 }
481 if (!builder.Write()) {
482 return device->WriteFail("Failed to write partition table");
483 }
484 return device->WriteOkay("Partition created");
485}
486
487bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
488 if (args.size() < 2) {
489 return device->WriteFail("Invalid partition name and size");
490 }
491
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700492 if (GetDeviceLockStatus()) {
493 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
494 }
495
David Andersond25f1c32018-11-09 20:41:33 -0800496 std::string partition_name = args[1];
497
498 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700499 if (!builder.Valid()) {
500 return device->WriteFail("Could not open super partition");
501 }
David Andersond25f1c32018-11-09 20:41:33 -0800502 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700503 if (!builder.Write()) {
504 return device->WriteFail("Failed to write partition table");
505 }
506 return device->WriteOkay("Partition deleted");
507}
508
509bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
510 if (args.size() < 3) {
511 return device->WriteFail("Invalid partition name and size");
512 }
513
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700514 if (GetDeviceLockStatus()) {
515 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
516 }
517
David Anderson0d4277d2018-07-31 13:27:37 -0700518 uint64_t partition_size;
519 std::string partition_name = args[1];
520 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
521 return device->WriteFail("Invalid partition size");
522 }
523
David Andersond25f1c32018-11-09 20:41:33 -0800524 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700525 if (!builder.Valid()) {
526 return device->WriteFail("Could not open super partition");
527 }
528
David Anderson27475322019-06-11 14:00:08 -0700529 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700530 if (!partition) {
531 return device->WriteFail("Partition does not exist");
532 }
David Andersonad970fc2019-08-27 14:01:16 -0700533
534 // Remove the updated flag to cancel any snapshots.
535 uint32_t attrs = partition->attributes();
536 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
537
David Anderson0d4277d2018-07-31 13:27:37 -0700538 if (!builder->ResizePartition(partition, partition_size)) {
539 return device->WriteFail("Not enough space to resize partition");
540 }
541 if (!builder.Write()) {
542 return device->WriteFail("Failed to write partition table");
543 }
544 return device->WriteOkay("Partition resized");
545}
David Anderson38b3c7a2018-08-15 16:27:42 -0700546
David Andersonad970fc2019-08-27 14:01:16 -0700547void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
548 PartitionBuilder builder(device, partition_name);
549 if (!builder.Valid()) return;
550
551 auto partition = builder->FindPartition(partition_name);
552 if (!partition) return;
553
554 // Remove the updated flag to cancel any snapshots.
555 uint32_t attrs = partition->attributes();
556 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
557
558 builder.Write();
559}
560
561bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
562 if (args.size() < 2) {
563 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
564 }
565
566 if (GetDeviceLockStatus()) {
567 return device->WriteStatus(FastbootResult::FAIL,
568 "Flashing is not allowed on locked devices");
569 }
570
571 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700572 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
573 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
574 return device->WriteFail(message);
575 }
576
David Andersonad970fc2019-08-27 14:01:16 -0700577 if (LogicalPartitionExists(device, partition_name)) {
578 CancelPartitionSnapshot(device, partition_name);
579 }
580
581 int ret = Flash(device, partition_name);
582 if (ret < 0) {
583 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
584 }
585 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
586}
587
David Anderson38b3c7a2018-08-15 16:27:42 -0700588bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
589 if (args.size() < 2) {
590 return device->WriteFail("Invalid arguments");
591 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700592
593 if (GetDeviceLockStatus()) {
594 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
595 }
596
David Anderson38b3c7a2018-08-15 16:27:42 -0700597 bool wipe = (args.size() >= 3 && args[2] == "wipe");
598 return UpdateSuper(device, args[1], wipe);
599}
David Anderson1d504e32019-01-15 14:38:20 -0800600
David Anderson3d782d52019-01-29 13:09:49 -0800601bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800602 if (args.size() != 2) {
603 return device->WriteFail("Invalid arguments");
604 }
David Anderson3d782d52019-01-29 13:09:49 -0800605
606 AutoMountMetadata mount_metadata;
607 if (!mount_metadata) {
608 return device->WriteFail("Could not find GSI install");
609 }
610
611 if (!android::gsi::IsGsiInstalled()) {
612 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
613 }
614
David Anderson1d504e32019-01-15 14:38:20 -0800615 if (args[1] == "wipe") {
616 if (!android::gsi::UninstallGsi()) {
617 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
618 }
619 } else if (args[1] == "disable") {
620 if (!android::gsi::DisableGsi()) {
621 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
622 }
623 }
624 return device->WriteStatus(FastbootResult::OKAY, "Success");
625}
David Andersonab8f4662019-10-21 16:45:59 -0700626
627bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
628 // Note that we use the HAL rather than mounting /metadata, since we want
629 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700630 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700631 if (!hal) return device->WriteFail("Not supported");
632
David Andersonab8f4662019-10-21 16:45:59 -0700633 // If no arguments, return the same thing as a getvar. Note that we get the
634 // HAL first so we can return "not supported" before we return the less
635 // specific error message below.
636 if (args.size() < 2 || args[1].empty()) {
637 std::string message;
638 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
639 return device->WriteFail("Could not determine update status");
640 }
641 device->WriteInfo(message);
642 return device->WriteOkay("");
643 }
644
David Anderson220ddb12019-10-31 18:02:41 -0700645 MergeStatus status = hal->getSnapshotMergeStatus();
646
647 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700648 return device->WriteFail("Invalid arguments");
649 }
David Anderson220ddb12019-10-31 18:02:41 -0700650 if (args[1] == "cancel") {
651 switch (status) {
652 case MergeStatus::SNAPSHOTTED:
653 case MergeStatus::MERGING:
654 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
655 break;
656 default:
657 break;
658 }
659 } else if (args[1] == "merge") {
660 if (status != MergeStatus::MERGING) {
661 return device->WriteFail("No snapshot merge is in progress");
662 }
David Andersonab8f4662019-10-21 16:45:59 -0700663
David Anderson565577f2021-02-04 20:14:18 -0800664 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700665 if (!sm) {
666 return device->WriteFail("Unable to create SnapshotManager");
667 }
David Anderson5a0177d2020-04-30 18:53:23 -0700668 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700669 return device->WriteFail("Unable to finish snapshot merge");
670 }
671 } else {
672 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700673 }
674 return device->WriteStatus(FastbootResult::OKAY, "Success");
675}