blob: b2b6a9e5cb65dd976d7027807706659ce4f544bf [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}},
139 {FB_VAR_TREBLE_ENABLED, {GetTrebleEnabled, nullptr}}};
David Anderson0f626632018-08-31 16:44:25 -0700140
141 if (args.size() < 2) {
142 return device->WriteFail("Missing argument");
143 }
144
145 // Special case: return all variables that we can.
146 if (args[1] == "all") {
147 for (const auto& [name, handlers] : kVariableMap) {
148 GetAllVars(device, name, handlers);
149 }
150 return device->WriteOkay("");
151 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700152
153 // args[0] is command name, args[1] is variable.
154 auto found_variable = kVariableMap.find(args[1]);
155 if (found_variable == kVariableMap.end()) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700156 return device->WriteFail("Unknown variable");
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700157 }
158
David Anderson1fb3fd72018-08-31 14:40:22 -0700159 std::string message;
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700160 std::vector<std::string> getvar_args(args.begin() + 2, args.end());
David Anderson0f626632018-08-31 16:44:25 -0700161 if (!found_variable->second.get(device, getvar_args, &message)) {
David Anderson1fb3fd72018-08-31 14:40:22 -0700162 return device->WriteFail(message);
163 }
164 return device->WriteOkay(message);
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700165}
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700166
josephjang29069752020-09-23 16:28:03 +0800167bool OemPostWipeData(FastbootDevice* device) {
168 auto fastboot_hal = device->fastboot_hal();
169 if (!fastboot_hal) {
170 return false;
171 }
172
173 Result ret;
174 auto ret_val = fastboot_hal->doOemSpecificErase([&](Result result) { ret = result; });
175 if (!ret_val.isOk()) {
176 return false;
177 }
178 if (ret.status == Status::NOT_SUPPORTED) {
179 return false;
180 } else if (ret.status != Status::SUCCESS) {
181 device->WriteStatus(FastbootResult::FAIL, ret.message);
182 } else {
183 device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
184 }
185
186 return true;
187}
188
David Anderson12211d12018-07-24 15:21:20 -0700189bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
190 if (args.size() < 2) {
191 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
192 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700193
194 if (GetDeviceLockStatus()) {
195 return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
196 }
197
David Anderson220ddb12019-10-31 18:02:41 -0700198 const auto& partition_name = args[1];
199 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
200 auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
201 return device->WriteFail(message);
202 }
203
David Anderson12211d12018-07-24 15:21:20 -0700204 PartitionHandle handle;
David Anderson220ddb12019-10-31 18:02:41 -0700205 if (!OpenPartition(device, partition_name, &handle)) {
David Anderson12211d12018-07-24 15:21:20 -0700206 return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
207 }
208 if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
josephjang29069752020-09-23 16:28:03 +0800209 //Perform oem PostWipeData if Android userdata partition has been erased
210 bool support_oem_postwipedata = false;
211 if (partition_name == "userdata") {
212 support_oem_postwipedata = OemPostWipeData(device);
213 }
214
215 if (!support_oem_postwipedata) {
216 return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
217 } else {
218 //Write device status in OemPostWipeData(), so just return true
219 return true;
220 }
David Anderson12211d12018-07-24 15:21:20 -0700221 }
222 return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
223}
224
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700225bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
226 auto fastboot_hal = device->fastboot_hal();
227 if (!fastboot_hal) {
228 return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
229 }
230
josephjangad90b452020-09-16 16:27:42 +0800231 //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
232 if (args[0] == "oem postwipedata userdata") {
233 return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
234 }
235
Hridya Valsarajua15fe312018-09-14 13:58:21 -0700236 Result ret;
237 auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
238 if (!ret_val.isOk()) {
239 return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
240 }
241 if (ret.status != Status::SUCCESS) {
242 return device->WriteStatus(FastbootResult::FAIL, ret.message);
243 }
244
245 return device->WriteStatus(FastbootResult::OKAY, ret.message);
246}
247
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700248bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
249 if (args.size() < 2) {
250 return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
251 }
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700252
253 if (GetDeviceLockStatus()) {
254 return device->WriteStatus(FastbootResult::FAIL,
255 "Download is not allowed on locked devices");
256 }
257
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700258 // arg[0] is the command name, arg[1] contains size of data to be downloaded
259 unsigned int size;
Hridya Valsarajuaae84e82018-10-08 13:10:25 -0700260 if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700261 return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
262 }
David Anderson12211d12018-07-24 15:21:20 -0700263 device->download_data().resize(size);
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700264 if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
265 return false;
266 }
267
David Anderson12211d12018-07-24 15:21:20 -0700268 if (device->HandleData(true, &device->download_data())) {
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700269 return device->WriteStatus(FastbootResult::OKAY, "");
270 }
271
272 PLOG(ERROR) << "Couldn't download data";
273 return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
274}
275
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700276bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
277 if (args.size() < 2) {
278 return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
279 }
280
Hridya Valsarajud1e62312018-10-08 09:13:17 -0700281 if (GetDeviceLockStatus()) {
282 return device->WriteStatus(FastbootResult::FAIL,
283 "set_active command is not allowed on locked devices");
284 }
285
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700286 Slot slot;
287 if (!GetSlotNumber(args[1], &slot)) {
David Anderson220ddb12019-10-31 18:02:41 -0700288 // Slot suffix needs to be between 'a' and 'z'.
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700289 return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
290 }
291
292 // Non-A/B devices will not have a boot control HAL.
293 auto boot_control_hal = device->boot_control_hal();
294 if (!boot_control_hal) {
295 return device->WriteStatus(FastbootResult::FAIL,
296 "Cannot set slot: boot control HAL absent");
297 }
298 if (slot >= boot_control_hal->getNumberSlots()) {
299 return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
300 }
David Anderson220ddb12019-10-31 18:02:41 -0700301
302 // If the slot is not changing, do nothing.
Hridya Valsaraju45719a82020-03-02 13:03:47 -0800303 if (args[1] == device->GetCurrentSlot()) {
David Anderson220ddb12019-10-31 18:02:41 -0700304 return device->WriteOkay("");
305 }
306
307 // Check how to handle the current snapshot state.
308 if (auto hal11 = device->boot1_1()) {
309 auto merge_status = hal11->getSnapshotMergeStatus();
310 if (merge_status == MergeStatus::MERGING) {
311 return device->WriteFail("Cannot change slots while a snapshot update is in progress");
312 }
313 // Note: we allow the slot change if the state is SNAPSHOTTED. First-
314 // stage init does not have access to the HAL, and uses the slot number
315 // and /metadata OTA state to determine whether a slot change occurred.
316 // Booting into the old slot would erase the OTA, and switching A->B->A
317 // would simply resume it if no boots occur in between. Re-flashing
318 // partitions implicitly cancels the OTA, so leaving the state as-is is
319 // safe.
320 if (merge_status == MergeStatus::SNAPSHOTTED) {
321 device->WriteInfo(
322 "Changing the active slot with a snapshot applied may cancel the"
323 " update.");
324 }
325 }
326
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700327 CommandResult ret;
328 auto cb = [&ret](CommandResult result) { ret = result; };
329 auto result = boot_control_hal->setActiveBootSlot(slot, cb);
Hridya Valsaraju20bdf892018-10-10 11:02:19 -0700330 if (result.isOk() && ret.success) {
331 // Save as slot suffix to match the suffix format as returned from
332 // the boot control HAL.
333 auto current_slot = "_" + args[1];
334 device->set_active_slot(current_slot);
335 return device->WriteStatus(FastbootResult::OKAY, "");
336 }
Hridya Valsaraju31d2c262018-07-20 13:35:50 -0700337 return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
Hridya Valsarajudea91b42018-07-17 11:14:01 -0700338}
339
340bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
341 auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
342 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
343 device->CloseDevice();
344 TEMP_FAILURE_RETRY(pause());
345 return result;
346}
347
348bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
349 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
350 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
351 device->CloseDevice();
352 TEMP_FAILURE_RETRY(pause());
353 return result;
354}
355
356bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
357 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
358 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
359 device->CloseDevice();
360 TEMP_FAILURE_RETRY(pause());
361 return result;
362}
363
364bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
365 auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
366 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
367 device->CloseDevice();
368 TEMP_FAILURE_RETRY(pause());
369 return result;
370}
371
372static bool EnterRecovery() {
373 const char msg_switch_to_recovery = 'r';
374
375 android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
376 if (sock < 0) {
377 PLOG(ERROR) << "Couldn't create sock";
378 return false;
379 }
380
381 struct sockaddr_un addr = {.sun_family = AF_UNIX};
382 strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
383 if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
384 PLOG(ERROR) << "Couldn't connect to recovery";
385 return false;
386 }
387 // Switch to recovery will not update the boot reason since it does not
388 // require a reboot.
389 auto ret = write(sock, &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
390 if (ret != sizeof(msg_switch_to_recovery)) {
391 PLOG(ERROR) << "Couldn't write message to switch to recovery";
392 return false;
393 }
394
395 return true;
396}
397
398bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
399 auto status = true;
400 if (EnterRecovery()) {
401 status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
402 } else {
403 status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
404 }
405 device->CloseDevice();
406 TEMP_FAILURE_RETRY(pause());
407 return status;
408}
David Anderson0d4277d2018-07-31 13:27:37 -0700409
410// Helper class for opening a handle to a MetadataBuilder and writing the new
411// partition table to the same place it was read.
412class PartitionBuilder {
413 public:
David Andersond25f1c32018-11-09 20:41:33 -0800414 explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700415
416 bool Write();
417 bool Valid() const { return !!builder_; }
418 MetadataBuilder* operator->() const { return builder_.get(); }
419
420 private:
David Anderson4d307b02018-12-17 17:07:34 -0800421 FastbootDevice* device_;
David Anderson0d4277d2018-07-31 13:27:37 -0700422 std::string super_device_;
David Andersond25f1c32018-11-09 20:41:33 -0800423 uint32_t slot_number_;
David Anderson0d4277d2018-07-31 13:27:37 -0700424 std::unique_ptr<MetadataBuilder> builder_;
425};
426
David Anderson4d307b02018-12-17 17:07:34 -0800427PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
428 : device_(device) {
David Andersond25f1c32018-11-09 20:41:33 -0800429 std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
David Anderson27475322019-06-11 14:00:08 -0700430 slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
David Andersond25f1c32018-11-09 20:41:33 -0800431 auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
David Anderson0d4277d2018-07-31 13:27:37 -0700432 if (!super_device) {
433 return;
434 }
435 super_device_ = *super_device;
David Andersond25f1c32018-11-09 20:41:33 -0800436 builder_ = MetadataBuilder::New(super_device_, slot_number_);
David Anderson0d4277d2018-07-31 13:27:37 -0700437}
438
439bool PartitionBuilder::Write() {
David Anderson27475322019-06-11 14:00:08 -0700440 auto metadata = builder_->Export();
David Anderson0d4277d2018-07-31 13:27:37 -0700441 if (!metadata) {
442 return false;
443 }
David Anderson4d307b02018-12-17 17:07:34 -0800444 return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
David Anderson0d4277d2018-07-31 13:27:37 -0700445}
446
447bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
448 if (args.size() < 3) {
449 return device->WriteFail("Invalid partition name and size");
450 }
451
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700452 if (GetDeviceLockStatus()) {
453 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
454 }
455
David Anderson0d4277d2018-07-31 13:27:37 -0700456 uint64_t partition_size;
457 std::string partition_name = args[1];
458 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
459 return device->WriteFail("Invalid partition size");
460 }
461
David Andersond25f1c32018-11-09 20:41:33 -0800462 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700463 if (!builder.Valid()) {
464 return device->WriteFail("Could not open super partition");
465 }
466 // TODO(112433293) Disallow if the name is in the physical table as well.
467 if (builder->FindPartition(partition_name)) {
468 return device->WriteFail("Partition already exists");
469 }
470
David Anderson27475322019-06-11 14:00:08 -0700471 auto partition = builder->AddPartition(partition_name, 0);
David Anderson0d4277d2018-07-31 13:27:37 -0700472 if (!partition) {
473 return device->WriteFail("Failed to add partition");
474 }
475 if (!builder->ResizePartition(partition, partition_size)) {
476 builder->RemovePartition(partition_name);
477 return device->WriteFail("Not enough space for partition");
478 }
479 if (!builder.Write()) {
480 return device->WriteFail("Failed to write partition table");
481 }
482 return device->WriteOkay("Partition created");
483}
484
485bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
486 if (args.size() < 2) {
487 return device->WriteFail("Invalid partition name and size");
488 }
489
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700490 if (GetDeviceLockStatus()) {
491 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
492 }
493
David Andersond25f1c32018-11-09 20:41:33 -0800494 std::string partition_name = args[1];
495
496 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700497 if (!builder.Valid()) {
498 return device->WriteFail("Could not open super partition");
499 }
David Andersond25f1c32018-11-09 20:41:33 -0800500 builder->RemovePartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700501 if (!builder.Write()) {
502 return device->WriteFail("Failed to write partition table");
503 }
504 return device->WriteOkay("Partition deleted");
505}
506
507bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
508 if (args.size() < 3) {
509 return device->WriteFail("Invalid partition name and size");
510 }
511
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700512 if (GetDeviceLockStatus()) {
513 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
514 }
515
David Anderson0d4277d2018-07-31 13:27:37 -0700516 uint64_t partition_size;
517 std::string partition_name = args[1];
518 if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
519 return device->WriteFail("Invalid partition size");
520 }
521
David Andersond25f1c32018-11-09 20:41:33 -0800522 PartitionBuilder builder(device, partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700523 if (!builder.Valid()) {
524 return device->WriteFail("Could not open super partition");
525 }
526
David Anderson27475322019-06-11 14:00:08 -0700527 auto partition = builder->FindPartition(partition_name);
David Anderson0d4277d2018-07-31 13:27:37 -0700528 if (!partition) {
529 return device->WriteFail("Partition does not exist");
530 }
David Andersonad970fc2019-08-27 14:01:16 -0700531
532 // Remove the updated flag to cancel any snapshots.
533 uint32_t attrs = partition->attributes();
534 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
535
David Anderson0d4277d2018-07-31 13:27:37 -0700536 if (!builder->ResizePartition(partition, partition_size)) {
537 return device->WriteFail("Not enough space to resize partition");
538 }
539 if (!builder.Write()) {
540 return device->WriteFail("Failed to write partition table");
541 }
542 return device->WriteOkay("Partition resized");
543}
David Anderson38b3c7a2018-08-15 16:27:42 -0700544
David Andersonad970fc2019-08-27 14:01:16 -0700545void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
546 PartitionBuilder builder(device, partition_name);
547 if (!builder.Valid()) return;
548
549 auto partition = builder->FindPartition(partition_name);
550 if (!partition) return;
551
552 // Remove the updated flag to cancel any snapshots.
553 uint32_t attrs = partition->attributes();
554 partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
555
556 builder.Write();
557}
558
559bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
560 if (args.size() < 2) {
561 return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
562 }
563
564 if (GetDeviceLockStatus()) {
565 return device->WriteStatus(FastbootResult::FAIL,
566 "Flashing is not allowed on locked devices");
567 }
568
569 const auto& partition_name = args[1];
David Anderson220ddb12019-10-31 18:02:41 -0700570 if (IsProtectedPartitionDuringMerge(device, partition_name)) {
571 auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
572 return device->WriteFail(message);
573 }
574
David Andersonad970fc2019-08-27 14:01:16 -0700575 if (LogicalPartitionExists(device, partition_name)) {
576 CancelPartitionSnapshot(device, partition_name);
577 }
578
579 int ret = Flash(device, partition_name);
580 if (ret < 0) {
581 return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
582 }
583 return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
584}
585
David Anderson38b3c7a2018-08-15 16:27:42 -0700586bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
587 if (args.size() < 2) {
588 return device->WriteFail("Invalid arguments");
589 }
Hridya Valsarajudca328d2018-09-24 16:01:35 -0700590
591 if (GetDeviceLockStatus()) {
592 return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
593 }
594
David Anderson38b3c7a2018-08-15 16:27:42 -0700595 bool wipe = (args.size() >= 3 && args[2] == "wipe");
596 return UpdateSuper(device, args[1], wipe);
597}
David Anderson1d504e32019-01-15 14:38:20 -0800598
David Anderson3d782d52019-01-29 13:09:49 -0800599bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
David Anderson1d504e32019-01-15 14:38:20 -0800600 if (args.size() != 2) {
601 return device->WriteFail("Invalid arguments");
602 }
David Anderson3d782d52019-01-29 13:09:49 -0800603
604 AutoMountMetadata mount_metadata;
605 if (!mount_metadata) {
606 return device->WriteFail("Could not find GSI install");
607 }
608
609 if (!android::gsi::IsGsiInstalled()) {
610 return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
611 }
612
David Anderson1d504e32019-01-15 14:38:20 -0800613 if (args[1] == "wipe") {
614 if (!android::gsi::UninstallGsi()) {
615 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
616 }
617 } else if (args[1] == "disable") {
618 if (!android::gsi::DisableGsi()) {
619 return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
620 }
621 }
622 return device->WriteStatus(FastbootResult::OKAY, "Success");
623}
David Andersonab8f4662019-10-21 16:45:59 -0700624
625bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
626 // Note that we use the HAL rather than mounting /metadata, since we want
627 // our results to match the bootloader.
David Anderson220ddb12019-10-31 18:02:41 -0700628 auto hal = device->boot1_1();
David Andersonab8f4662019-10-21 16:45:59 -0700629 if (!hal) return device->WriteFail("Not supported");
630
David Andersonab8f4662019-10-21 16:45:59 -0700631 // If no arguments, return the same thing as a getvar. Note that we get the
632 // HAL first so we can return "not supported" before we return the less
633 // specific error message below.
634 if (args.size() < 2 || args[1].empty()) {
635 std::string message;
636 if (!GetSnapshotUpdateStatus(device, {}, &message)) {
637 return device->WriteFail("Could not determine update status");
638 }
639 device->WriteInfo(message);
640 return device->WriteOkay("");
641 }
642
David Anderson220ddb12019-10-31 18:02:41 -0700643 MergeStatus status = hal->getSnapshotMergeStatus();
644
645 if (args.size() != 2) {
David Andersonab8f4662019-10-21 16:45:59 -0700646 return device->WriteFail("Invalid arguments");
647 }
David Anderson220ddb12019-10-31 18:02:41 -0700648 if (args[1] == "cancel") {
649 switch (status) {
650 case MergeStatus::SNAPSHOTTED:
651 case MergeStatus::MERGING:
652 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
653 break;
654 default:
655 break;
656 }
657 } else if (args[1] == "merge") {
658 if (status != MergeStatus::MERGING) {
659 return device->WriteFail("No snapshot merge is in progress");
660 }
David Andersonab8f4662019-10-21 16:45:59 -0700661
David Anderson565577f2021-02-04 20:14:18 -0800662 auto sm = SnapshotManager::New();
David Anderson220ddb12019-10-31 18:02:41 -0700663 if (!sm) {
664 return device->WriteFail("Unable to create SnapshotManager");
665 }
David Anderson5a0177d2020-04-30 18:53:23 -0700666 if (!sm->FinishMergeInRecovery()) {
David Anderson220ddb12019-10-31 18:02:41 -0700667 return device->WriteFail("Unable to finish snapshot merge");
668 }
669 } else {
670 return device->WriteFail("Invalid parameter to snapshot-update");
David Andersonab8f4662019-10-21 16:45:59 -0700671 }
672 return device->WriteStatus(FastbootResult::OKAY, "Success");
673}