1 /*
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 
22 #include <unordered_set>
23 
24 #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>
30 #include <android/hardware/boot/1.1/IBootControl.h>
31 #include <cutils/android_reboot.h>
32 #include <ext4_utils/wipe.h>
33 #include <fs_mgr.h>
34 #include <fs_mgr/roots.h>
35 #include <libgsi/libgsi.h>
36 #include <liblp/builder.h>
37 #include <liblp/liblp.h>
38 #include <libsnapshot/snapshot.h>
39 #include <uuid/uuid.h>
40 
41 #include "constants.h"
42 #include "fastboot_device.h"
43 #include "flashing.h"
44 #include "utility.h"
45 
46 using android::fs_mgr::MetadataBuilder;
47 using ::android::hardware::hidl_string;
48 using ::android::hardware::boot::V1_0::BoolResult;
49 using ::android::hardware::boot::V1_0::CommandResult;
50 using ::android::hardware::boot::V1_0::Slot;
51 using ::android::hardware::boot::V1_1::MergeStatus;
52 using ::android::hardware::fastboot::V1_0::Result;
53 using ::android::hardware::fastboot::V1_0::Status;
54 using android::snapshot::SnapshotManager;
55 using IBootControl1_1 = ::android::hardware::boot::V1_1::IBootControl;
56 
57 struct 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 
IsSnapshotUpdateInProgress(FastbootDevice * device)64 static 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 
IsProtectedPartitionDuringMerge(FastbootDevice * device,const std::string & name)73 static 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 
GetAllVars(FastbootDevice * device,const std::string & name,const VariableHandlers & handlers)82 static 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 
GetVarHandler(FastbootDevice * device,const std::vector<std::string> & args)105 bool GetVarHandler(FastbootDevice* device, const std::vector<std::string>& args) {
106     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}},
110             {FB_VAR_VERSION_OS, {GetOsVersion, nullptr}},
111             {FB_VAR_VERSION_VNDK, {GetVndkVersion, nullptr}},
112             {FB_VAR_PRODUCT, {GetProduct, nullptr}},
113             {FB_VAR_SERIALNO, {GetSerial, nullptr}},
114             {FB_VAR_VARIANT, {GetVariant, nullptr}},
115             {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}},
123             {FB_VAR_PARTITION_SIZE, {GetPartitionSize, GetAllPartitionArgsWithSlot}},
124             {FB_VAR_PARTITION_TYPE, {GetPartitionType, GetAllPartitionArgsWithSlot}},
125             {FB_VAR_IS_LOGICAL, {GetPartitionIsLogical, GetAllPartitionArgsWithSlot}},
126             {FB_VAR_IS_USERSPACE, {GetIsUserspace, nullptr}},
127             {FB_VAR_OFF_MODE_CHARGE_STATE, {GetOffModeChargeState, nullptr}},
128             {FB_VAR_BATTERY_VOLTAGE, {GetBatteryVoltage, nullptr}},
129             {FB_VAR_BATTERY_SOC_OK, {GetBatterySoCOk, nullptr}},
130             {FB_VAR_HW_REVISION, {GetHardwareRevision, nullptr}},
131             {FB_VAR_SUPER_PARTITION_NAME, {GetSuperPartitionName, nullptr}},
132             {FB_VAR_SNAPSHOT_UPDATE_STATUS, {GetSnapshotUpdateStatus, nullptr}},
133             {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}}};
140 
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     }
152 
153     // args[0] is command name, args[1] is variable.
154     auto found_variable = kVariableMap.find(args[1]);
155     if (found_variable == kVariableMap.end()) {
156         return device->WriteFail("Unknown variable");
157     }
158 
159     std::string message;
160     std::vector<std::string> getvar_args(args.begin() + 2, args.end());
161     if (!found_variable->second.get(device, getvar_args, &message)) {
162         return device->WriteFail(message);
163     }
164     return device->WriteOkay(message);
165 }
166 
EraseHandler(FastbootDevice * device,const std::vector<std::string> & args)167 bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
168     if (args.size() < 2) {
169         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
170     }
171 
172     if (GetDeviceLockStatus()) {
173         return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
174     }
175 
176     const auto& partition_name = args[1];
177     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
178         auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
179         return device->WriteFail(message);
180     }
181 
182     PartitionHandle handle;
183     if (!OpenPartition(device, partition_name, &handle)) {
184         return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
185     }
186     if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
187         return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
188     }
189     return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
190 }
191 
OemCmdHandler(FastbootDevice * device,const std::vector<std::string> & args)192 bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
193     auto fastboot_hal = device->fastboot_hal();
194     if (!fastboot_hal) {
195         return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
196     }
197 
198     Result ret;
199     auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
200     if (!ret_val.isOk()) {
201         return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
202     }
203     if (ret.status != Status::SUCCESS) {
204         return device->WriteStatus(FastbootResult::FAIL, ret.message);
205     }
206 
207     return device->WriteStatus(FastbootResult::OKAY, ret.message);
208 }
209 
DownloadHandler(FastbootDevice * device,const std::vector<std::string> & args)210 bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
211     if (args.size() < 2) {
212         return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
213     }
214 
215     if (GetDeviceLockStatus()) {
216         return device->WriteStatus(FastbootResult::FAIL,
217                                    "Download is not allowed on locked devices");
218     }
219 
220     // arg[0] is the command name, arg[1] contains size of data to be downloaded
221     unsigned int size;
222     if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
223         return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
224     }
225     device->download_data().resize(size);
226     if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
227         return false;
228     }
229 
230     if (device->HandleData(true, &device->download_data())) {
231         return device->WriteStatus(FastbootResult::OKAY, "");
232     }
233 
234     PLOG(ERROR) << "Couldn't download data";
235     return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
236 }
237 
SetActiveHandler(FastbootDevice * device,const std::vector<std::string> & args)238 bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
239     if (args.size() < 2) {
240         return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
241     }
242 
243     if (GetDeviceLockStatus()) {
244         return device->WriteStatus(FastbootResult::FAIL,
245                                    "set_active command is not allowed on locked devices");
246     }
247 
248     Slot slot;
249     if (!GetSlotNumber(args[1], &slot)) {
250         // Slot suffix needs to be between 'a' and 'z'.
251         return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
252     }
253 
254     // Non-A/B devices will not have a boot control HAL.
255     auto boot_control_hal = device->boot_control_hal();
256     if (!boot_control_hal) {
257         return device->WriteStatus(FastbootResult::FAIL,
258                                    "Cannot set slot: boot control HAL absent");
259     }
260     if (slot >= boot_control_hal->getNumberSlots()) {
261         return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
262     }
263 
264     // If the slot is not changing, do nothing.
265     if (args[1] == device->GetCurrentSlot()) {
266         return device->WriteOkay("");
267     }
268 
269     // Check how to handle the current snapshot state.
270     if (auto hal11 = device->boot1_1()) {
271         auto merge_status = hal11->getSnapshotMergeStatus();
272         if (merge_status == MergeStatus::MERGING) {
273             return device->WriteFail("Cannot change slots while a snapshot update is in progress");
274         }
275         // Note: we allow the slot change if the state is SNAPSHOTTED. First-
276         // stage init does not have access to the HAL, and uses the slot number
277         // and /metadata OTA state to determine whether a slot change occurred.
278         // Booting into the old slot would erase the OTA, and switching A->B->A
279         // would simply resume it if no boots occur in between. Re-flashing
280         // partitions implicitly cancels the OTA, so leaving the state as-is is
281         // safe.
282         if (merge_status == MergeStatus::SNAPSHOTTED) {
283             device->WriteInfo(
284                     "Changing the active slot with a snapshot applied may cancel the"
285                     " update.");
286         }
287     }
288 
289     CommandResult ret;
290     auto cb = [&ret](CommandResult result) { ret = result; };
291     auto result = boot_control_hal->setActiveBootSlot(slot, cb);
292     if (result.isOk() && ret.success) {
293         // Save as slot suffix to match the suffix format as returned from
294         // the boot control HAL.
295         auto current_slot = "_" + args[1];
296         device->set_active_slot(current_slot);
297         return device->WriteStatus(FastbootResult::OKAY, "");
298     }
299     return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
300 }
301 
ShutDownHandler(FastbootDevice * device,const std::vector<std::string> &)302 bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
303     auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
304     android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
305     device->CloseDevice();
306     TEMP_FAILURE_RETRY(pause());
307     return result;
308 }
309 
RebootHandler(FastbootDevice * device,const std::vector<std::string> &)310 bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
311     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
312     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
313     device->CloseDevice();
314     TEMP_FAILURE_RETRY(pause());
315     return result;
316 }
317 
RebootBootloaderHandler(FastbootDevice * device,const std::vector<std::string> &)318 bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
319     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
320     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
321     device->CloseDevice();
322     TEMP_FAILURE_RETRY(pause());
323     return result;
324 }
325 
RebootFastbootHandler(FastbootDevice * device,const std::vector<std::string> &)326 bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
327     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
328     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
329     device->CloseDevice();
330     TEMP_FAILURE_RETRY(pause());
331     return result;
332 }
333 
EnterRecovery()334 static bool EnterRecovery() {
335     const char msg_switch_to_recovery = 'r';
336 
337     android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
338     if (sock < 0) {
339         PLOG(ERROR) << "Couldn't create sock";
340         return false;
341     }
342 
343     struct sockaddr_un addr = {.sun_family = AF_UNIX};
344     strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
345     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
346         PLOG(ERROR) << "Couldn't connect to recovery";
347         return false;
348     }
349     // Switch to recovery will not update the boot reason since it does not
350     // require a reboot.
351     auto ret = write(sock, &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
352     if (ret != sizeof(msg_switch_to_recovery)) {
353         PLOG(ERROR) << "Couldn't write message to switch to recovery";
354         return false;
355     }
356 
357     return true;
358 }
359 
RebootRecoveryHandler(FastbootDevice * device,const std::vector<std::string> &)360 bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
361     auto status = true;
362     if (EnterRecovery()) {
363         status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
364     } else {
365         status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
366     }
367     device->CloseDevice();
368     TEMP_FAILURE_RETRY(pause());
369     return status;
370 }
371 
372 // Helper class for opening a handle to a MetadataBuilder and writing the new
373 // partition table to the same place it was read.
374 class PartitionBuilder {
375   public:
376     explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
377 
378     bool Write();
Valid() const379     bool Valid() const { return !!builder_; }
operator ->() const380     MetadataBuilder* operator->() const { return builder_.get(); }
381 
382   private:
383     FastbootDevice* device_;
384     std::string super_device_;
385     uint32_t slot_number_;
386     std::unique_ptr<MetadataBuilder> builder_;
387 };
388 
PartitionBuilder(FastbootDevice * device,const std::string & partition_name)389 PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
390     : device_(device) {
391     std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
392     slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
393     auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
394     if (!super_device) {
395         return;
396     }
397     super_device_ = *super_device;
398     builder_ = MetadataBuilder::New(super_device_, slot_number_);
399 }
400 
Write()401 bool PartitionBuilder::Write() {
402     auto metadata = builder_->Export();
403     if (!metadata) {
404         return false;
405     }
406     return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
407 }
408 
CreatePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)409 bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
410     if (args.size() < 3) {
411         return device->WriteFail("Invalid partition name and size");
412     }
413 
414     if (GetDeviceLockStatus()) {
415         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
416     }
417 
418     uint64_t partition_size;
419     std::string partition_name = args[1];
420     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
421         return device->WriteFail("Invalid partition size");
422     }
423 
424     PartitionBuilder builder(device, partition_name);
425     if (!builder.Valid()) {
426         return device->WriteFail("Could not open super partition");
427     }
428     // TODO(112433293) Disallow if the name is in the physical table as well.
429     if (builder->FindPartition(partition_name)) {
430         return device->WriteFail("Partition already exists");
431     }
432 
433     auto partition = builder->AddPartition(partition_name, 0);
434     if (!partition) {
435         return device->WriteFail("Failed to add partition");
436     }
437     if (!builder->ResizePartition(partition, partition_size)) {
438         builder->RemovePartition(partition_name);
439         return device->WriteFail("Not enough space for partition");
440     }
441     if (!builder.Write()) {
442         return device->WriteFail("Failed to write partition table");
443     }
444     return device->WriteOkay("Partition created");
445 }
446 
DeletePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)447 bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
448     if (args.size() < 2) {
449         return device->WriteFail("Invalid partition name and size");
450     }
451 
452     if (GetDeviceLockStatus()) {
453         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
454     }
455 
456     std::string partition_name = args[1];
457 
458     PartitionBuilder builder(device, partition_name);
459     if (!builder.Valid()) {
460         return device->WriteFail("Could not open super partition");
461     }
462     builder->RemovePartition(partition_name);
463     if (!builder.Write()) {
464         return device->WriteFail("Failed to write partition table");
465     }
466     return device->WriteOkay("Partition deleted");
467 }
468 
ResizePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)469 bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
470     if (args.size() < 3) {
471         return device->WriteFail("Invalid partition name and size");
472     }
473 
474     if (GetDeviceLockStatus()) {
475         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
476     }
477 
478     uint64_t partition_size;
479     std::string partition_name = args[1];
480     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
481         return device->WriteFail("Invalid partition size");
482     }
483 
484     PartitionBuilder builder(device, partition_name);
485     if (!builder.Valid()) {
486         return device->WriteFail("Could not open super partition");
487     }
488 
489     auto partition = builder->FindPartition(partition_name);
490     if (!partition) {
491         return device->WriteFail("Partition does not exist");
492     }
493 
494     // Remove the updated flag to cancel any snapshots.
495     uint32_t attrs = partition->attributes();
496     partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
497 
498     if (!builder->ResizePartition(partition, partition_size)) {
499         return device->WriteFail("Not enough space to resize partition");
500     }
501     if (!builder.Write()) {
502         return device->WriteFail("Failed to write partition table");
503     }
504     return device->WriteOkay("Partition resized");
505 }
506 
CancelPartitionSnapshot(FastbootDevice * device,const std::string & partition_name)507 void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
508     PartitionBuilder builder(device, partition_name);
509     if (!builder.Valid()) return;
510 
511     auto partition = builder->FindPartition(partition_name);
512     if (!partition) return;
513 
514     // Remove the updated flag to cancel any snapshots.
515     uint32_t attrs = partition->attributes();
516     partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
517 
518     builder.Write();
519 }
520 
FlashHandler(FastbootDevice * device,const std::vector<std::string> & args)521 bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
522     if (args.size() < 2) {
523         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
524     }
525 
526     if (GetDeviceLockStatus()) {
527         return device->WriteStatus(FastbootResult::FAIL,
528                                    "Flashing is not allowed on locked devices");
529     }
530 
531     const auto& partition_name = args[1];
532     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
533         auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
534         return device->WriteFail(message);
535     }
536 
537     if (LogicalPartitionExists(device, partition_name)) {
538         CancelPartitionSnapshot(device, partition_name);
539     }
540 
541     int ret = Flash(device, partition_name);
542     if (ret < 0) {
543         return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
544     }
545     return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
546 }
547 
UpdateSuperHandler(FastbootDevice * device,const std::vector<std::string> & args)548 bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
549     if (args.size() < 2) {
550         return device->WriteFail("Invalid arguments");
551     }
552 
553     if (GetDeviceLockStatus()) {
554         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
555     }
556 
557     bool wipe = (args.size() >= 3 && args[2] == "wipe");
558     return UpdateSuper(device, args[1], wipe);
559 }
560 
GsiHandler(FastbootDevice * device,const std::vector<std::string> & args)561 bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
562     if (args.size() != 2) {
563         return device->WriteFail("Invalid arguments");
564     }
565 
566     AutoMountMetadata mount_metadata;
567     if (!mount_metadata) {
568         return device->WriteFail("Could not find GSI install");
569     }
570 
571     if (!android::gsi::IsGsiInstalled()) {
572         return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
573     }
574 
575     if (args[1] == "wipe") {
576         if (!android::gsi::UninstallGsi()) {
577             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
578         }
579     } else if (args[1] == "disable") {
580         if (!android::gsi::DisableGsi()) {
581             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
582         }
583     }
584     return device->WriteStatus(FastbootResult::OKAY, "Success");
585 }
586 
SnapshotUpdateHandler(FastbootDevice * device,const std::vector<std::string> & args)587 bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
588     // Note that we use the HAL rather than mounting /metadata, since we want
589     // our results to match the bootloader.
590     auto hal = device->boot1_1();
591     if (!hal) return device->WriteFail("Not supported");
592 
593     // If no arguments, return the same thing as a getvar. Note that we get the
594     // HAL first so we can return "not supported" before we return the less
595     // specific error message below.
596     if (args.size() < 2 || args[1].empty()) {
597         std::string message;
598         if (!GetSnapshotUpdateStatus(device, {}, &message)) {
599             return device->WriteFail("Could not determine update status");
600         }
601         device->WriteInfo(message);
602         return device->WriteOkay("");
603     }
604 
605     MergeStatus status = hal->getSnapshotMergeStatus();
606 
607     if (args.size() != 2) {
608         return device->WriteFail("Invalid arguments");
609     }
610     if (args[1] == "cancel") {
611         switch (status) {
612             case MergeStatus::SNAPSHOTTED:
613             case MergeStatus::MERGING:
614                 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
615                 break;
616             default:
617                 break;
618         }
619     } else if (args[1] == "merge") {
620         if (status != MergeStatus::MERGING) {
621             return device->WriteFail("No snapshot merge is in progress");
622         }
623 
624         auto sm = SnapshotManager::NewForFirstStageMount();
625         if (!sm) {
626             return device->WriteFail("Unable to create SnapshotManager");
627         }
628         if (!sm->FinishMergeInRecovery()) {
629             return device->WriteFail("Unable to finish snapshot merge");
630         }
631     } else {
632         return device->WriteFail("Invalid parameter to snapshot-update");
633     }
634     return device->WriteStatus(FastbootResult::OKAY, "Success");
635 }
636