• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
OemPostWipeData(FastbootDevice * device)167 bool OemPostWipeData(FastbootDevice* device) {
168     auto fastboot_hal = device->fastboot_hal();
169     if (!fastboot_hal) {
170         return false;
171     }
172 
173     Result ret;
174     // Check whether fastboot_hal support "oem postwipedata" API or not.
175     const std::string checkPostWipeDataCmd("oem postwipedata support");
176     auto check_cmd_ret_val = fastboot_hal->doOemCommand(checkPostWipeDataCmd,
177                                         [&](Result result) { ret = result; });
178     if (!check_cmd_ret_val.isOk()) {
179         return false;
180     }
181     if (ret.status != Status::SUCCESS) {
182         return false;
183     }
184 
185     const std::string postWipeDataCmd("oem postwipedata userdata");
186     auto ret_val = fastboot_hal->doOemCommand(postWipeDataCmd,
187                                         [&](Result result) { ret = result; });
188     if (!ret_val.isOk()) {
189         return false;
190     }
191     if (ret.status != Status::SUCCESS) {
192         device->WriteStatus(FastbootResult::FAIL, ret.message);
193     } else {
194         device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
195     }
196 
197     return true;
198 }
199 
EraseHandler(FastbootDevice * device,const std::vector<std::string> & args)200 bool EraseHandler(FastbootDevice* device, const std::vector<std::string>& args) {
201     if (args.size() < 2) {
202         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
203     }
204 
205     if (GetDeviceLockStatus()) {
206         return device->WriteStatus(FastbootResult::FAIL, "Erase is not allowed on locked devices");
207     }
208 
209     const auto& partition_name = args[1];
210     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
211         auto message = "Cannot erase " + partition_name + " while a snapshot update is in progress";
212         return device->WriteFail(message);
213     }
214 
215     PartitionHandle handle;
216     if (!OpenPartition(device, partition_name, &handle)) {
217         return device->WriteStatus(FastbootResult::FAIL, "Partition doesn't exist");
218     }
219     if (wipe_block_device(handle.fd(), get_block_device_size(handle.fd())) == 0) {
220         //Perform oem PostWipeData if Android userdata partition has been erased
221         bool support_oem_postwipedata = false;
222         if (partition_name == "userdata") {
223             support_oem_postwipedata = OemPostWipeData(device);
224         }
225 
226         if (!support_oem_postwipedata) {
227             return device->WriteStatus(FastbootResult::OKAY, "Erasing succeeded");
228         } else {
229             //Write device status in OemPostWipeData(), so just return true
230             return true;
231         }
232     }
233     return device->WriteStatus(FastbootResult::FAIL, "Erasing failed");
234 }
235 
OemCmdHandler(FastbootDevice * device,const std::vector<std::string> & args)236 bool OemCmdHandler(FastbootDevice* device, const std::vector<std::string>& args) {
237     auto fastboot_hal = device->fastboot_hal();
238     if (!fastboot_hal) {
239         return device->WriteStatus(FastbootResult::FAIL, "Unable to open fastboot HAL");
240     }
241 
242     //Disable "oem postwipedata userdata" to prevent user wipe oem userdata only.
243     if (args[0] == "oem postwipedata userdata") {
244         return device->WriteStatus(FastbootResult::FAIL, "Unable to do oem postwipedata userdata");
245     }
246 
247     Result ret;
248     auto ret_val = fastboot_hal->doOemCommand(args[0], [&](Result result) { ret = result; });
249     if (!ret_val.isOk()) {
250         return device->WriteStatus(FastbootResult::FAIL, "Unable to do OEM command");
251     }
252     if (ret.status != Status::SUCCESS) {
253         return device->WriteStatus(FastbootResult::FAIL, ret.message);
254     }
255 
256     return device->WriteStatus(FastbootResult::OKAY, ret.message);
257 }
258 
DownloadHandler(FastbootDevice * device,const std::vector<std::string> & args)259 bool DownloadHandler(FastbootDevice* device, const std::vector<std::string>& args) {
260     if (args.size() < 2) {
261         return device->WriteStatus(FastbootResult::FAIL, "size argument unspecified");
262     }
263 
264     if (GetDeviceLockStatus()) {
265         return device->WriteStatus(FastbootResult::FAIL,
266                                    "Download is not allowed on locked devices");
267     }
268 
269     // arg[0] is the command name, arg[1] contains size of data to be downloaded
270     unsigned int size;
271     if (!android::base::ParseUint("0x" + args[1], &size, kMaxDownloadSizeDefault)) {
272         return device->WriteStatus(FastbootResult::FAIL, "Invalid size");
273     }
274     device->download_data().resize(size);
275     if (!device->WriteStatus(FastbootResult::DATA, android::base::StringPrintf("%08x", size))) {
276         return false;
277     }
278 
279     if (device->HandleData(true, &device->download_data())) {
280         return device->WriteStatus(FastbootResult::OKAY, "");
281     }
282 
283     PLOG(ERROR) << "Couldn't download data";
284     return device->WriteStatus(FastbootResult::FAIL, "Couldn't download data");
285 }
286 
SetActiveHandler(FastbootDevice * device,const std::vector<std::string> & args)287 bool SetActiveHandler(FastbootDevice* device, const std::vector<std::string>& args) {
288     if (args.size() < 2) {
289         return device->WriteStatus(FastbootResult::FAIL, "Missing slot argument");
290     }
291 
292     if (GetDeviceLockStatus()) {
293         return device->WriteStatus(FastbootResult::FAIL,
294                                    "set_active command is not allowed on locked devices");
295     }
296 
297     Slot slot;
298     if (!GetSlotNumber(args[1], &slot)) {
299         // Slot suffix needs to be between 'a' and 'z'.
300         return device->WriteStatus(FastbootResult::FAIL, "Bad slot suffix");
301     }
302 
303     // Non-A/B devices will not have a boot control HAL.
304     auto boot_control_hal = device->boot_control_hal();
305     if (!boot_control_hal) {
306         return device->WriteStatus(FastbootResult::FAIL,
307                                    "Cannot set slot: boot control HAL absent");
308     }
309     if (slot >= boot_control_hal->getNumberSlots()) {
310         return device->WriteStatus(FastbootResult::FAIL, "Slot out of range");
311     }
312 
313     // If the slot is not changing, do nothing.
314     if (args[1] == device->GetCurrentSlot()) {
315         return device->WriteOkay("");
316     }
317 
318     // Check how to handle the current snapshot state.
319     if (auto hal11 = device->boot1_1()) {
320         auto merge_status = hal11->getSnapshotMergeStatus();
321         if (merge_status == MergeStatus::MERGING) {
322             return device->WriteFail("Cannot change slots while a snapshot update is in progress");
323         }
324         // Note: we allow the slot change if the state is SNAPSHOTTED. First-
325         // stage init does not have access to the HAL, and uses the slot number
326         // and /metadata OTA state to determine whether a slot change occurred.
327         // Booting into the old slot would erase the OTA, and switching A->B->A
328         // would simply resume it if no boots occur in between. Re-flashing
329         // partitions implicitly cancels the OTA, so leaving the state as-is is
330         // safe.
331         if (merge_status == MergeStatus::SNAPSHOTTED) {
332             device->WriteInfo(
333                     "Changing the active slot with a snapshot applied may cancel the"
334                     " update.");
335         }
336     }
337 
338     CommandResult ret;
339     auto cb = [&ret](CommandResult result) { ret = result; };
340     auto result = boot_control_hal->setActiveBootSlot(slot, cb);
341     if (result.isOk() && ret.success) {
342         // Save as slot suffix to match the suffix format as returned from
343         // the boot control HAL.
344         auto current_slot = "_" + args[1];
345         device->set_active_slot(current_slot);
346         return device->WriteStatus(FastbootResult::OKAY, "");
347     }
348     return device->WriteStatus(FastbootResult::FAIL, "Unable to set slot");
349 }
350 
ShutDownHandler(FastbootDevice * device,const std::vector<std::string> &)351 bool ShutDownHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
352     auto result = device->WriteStatus(FastbootResult::OKAY, "Shutting down");
353     android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,fastboot");
354     device->CloseDevice();
355     TEMP_FAILURE_RETRY(pause());
356     return result;
357 }
358 
RebootHandler(FastbootDevice * device,const std::vector<std::string> &)359 bool RebootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
360     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting");
361     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,from_fastboot");
362     device->CloseDevice();
363     TEMP_FAILURE_RETRY(pause());
364     return result;
365 }
366 
RebootBootloaderHandler(FastbootDevice * device,const std::vector<std::string> &)367 bool RebootBootloaderHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
368     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting bootloader");
369     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
370     device->CloseDevice();
371     TEMP_FAILURE_RETRY(pause());
372     return result;
373 }
374 
RebootFastbootHandler(FastbootDevice * device,const std::vector<std::string> &)375 bool RebootFastbootHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
376     auto result = device->WriteStatus(FastbootResult::OKAY, "Rebooting fastboot");
377     android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
378     device->CloseDevice();
379     TEMP_FAILURE_RETRY(pause());
380     return result;
381 }
382 
EnterRecovery()383 static bool EnterRecovery() {
384     const char msg_switch_to_recovery = 'r';
385 
386     android::base::unique_fd sock(socket(AF_UNIX, SOCK_STREAM, 0));
387     if (sock < 0) {
388         PLOG(ERROR) << "Couldn't create sock";
389         return false;
390     }
391 
392     struct sockaddr_un addr = {.sun_family = AF_UNIX};
393     strncpy(addr.sun_path, "/dev/socket/recovery", sizeof(addr.sun_path) - 1);
394     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
395         PLOG(ERROR) << "Couldn't connect to recovery";
396         return false;
397     }
398     // Switch to recovery will not update the boot reason since it does not
399     // require a reboot.
400     auto ret = write(sock, &msg_switch_to_recovery, sizeof(msg_switch_to_recovery));
401     if (ret != sizeof(msg_switch_to_recovery)) {
402         PLOG(ERROR) << "Couldn't write message to switch to recovery";
403         return false;
404     }
405 
406     return true;
407 }
408 
RebootRecoveryHandler(FastbootDevice * device,const std::vector<std::string> &)409 bool RebootRecoveryHandler(FastbootDevice* device, const std::vector<std::string>& /* args */) {
410     auto status = true;
411     if (EnterRecovery()) {
412         status = device->WriteStatus(FastbootResult::OKAY, "Rebooting to recovery");
413     } else {
414         status = device->WriteStatus(FastbootResult::FAIL, "Unable to reboot to recovery");
415     }
416     device->CloseDevice();
417     TEMP_FAILURE_RETRY(pause());
418     return status;
419 }
420 
421 // Helper class for opening a handle to a MetadataBuilder and writing the new
422 // partition table to the same place it was read.
423 class PartitionBuilder {
424   public:
425     explicit PartitionBuilder(FastbootDevice* device, const std::string& partition_name);
426 
427     bool Write();
Valid() const428     bool Valid() const { return !!builder_; }
operator ->() const429     MetadataBuilder* operator->() const { return builder_.get(); }
430 
431   private:
432     FastbootDevice* device_;
433     std::string super_device_;
434     uint32_t slot_number_;
435     std::unique_ptr<MetadataBuilder> builder_;
436 };
437 
PartitionBuilder(FastbootDevice * device,const std::string & partition_name)438 PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
439     : device_(device) {
440     std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
441     slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
442     auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
443     if (!super_device) {
444         return;
445     }
446     super_device_ = *super_device;
447     builder_ = MetadataBuilder::New(super_device_, slot_number_);
448 }
449 
Write()450 bool PartitionBuilder::Write() {
451     auto metadata = builder_->Export();
452     if (!metadata) {
453         return false;
454     }
455     return UpdateAllPartitionMetadata(device_, super_device_, *metadata.get());
456 }
457 
CreatePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)458 bool CreatePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
459     if (args.size() < 3) {
460         return device->WriteFail("Invalid partition name and size");
461     }
462 
463     if (GetDeviceLockStatus()) {
464         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
465     }
466 
467     uint64_t partition_size;
468     std::string partition_name = args[1];
469     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
470         return device->WriteFail("Invalid partition size");
471     }
472 
473     PartitionBuilder builder(device, partition_name);
474     if (!builder.Valid()) {
475         return device->WriteFail("Could not open super partition");
476     }
477     // TODO(112433293) Disallow if the name is in the physical table as well.
478     if (builder->FindPartition(partition_name)) {
479         return device->WriteFail("Partition already exists");
480     }
481 
482     auto partition = builder->AddPartition(partition_name, 0);
483     if (!partition) {
484         return device->WriteFail("Failed to add partition");
485     }
486     if (!builder->ResizePartition(partition, partition_size)) {
487         builder->RemovePartition(partition_name);
488         return device->WriteFail("Not enough space for partition");
489     }
490     if (!builder.Write()) {
491         return device->WriteFail("Failed to write partition table");
492     }
493     return device->WriteOkay("Partition created");
494 }
495 
DeletePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)496 bool DeletePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
497     if (args.size() < 2) {
498         return device->WriteFail("Invalid partition name and size");
499     }
500 
501     if (GetDeviceLockStatus()) {
502         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
503     }
504 
505     std::string partition_name = args[1];
506 
507     PartitionBuilder builder(device, partition_name);
508     if (!builder.Valid()) {
509         return device->WriteFail("Could not open super partition");
510     }
511     builder->RemovePartition(partition_name);
512     if (!builder.Write()) {
513         return device->WriteFail("Failed to write partition table");
514     }
515     return device->WriteOkay("Partition deleted");
516 }
517 
ResizePartitionHandler(FastbootDevice * device,const std::vector<std::string> & args)518 bool ResizePartitionHandler(FastbootDevice* device, const std::vector<std::string>& args) {
519     if (args.size() < 3) {
520         return device->WriteFail("Invalid partition name and size");
521     }
522 
523     if (GetDeviceLockStatus()) {
524         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
525     }
526 
527     uint64_t partition_size;
528     std::string partition_name = args[1];
529     if (!android::base::ParseUint(args[2].c_str(), &partition_size)) {
530         return device->WriteFail("Invalid partition size");
531     }
532 
533     PartitionBuilder builder(device, partition_name);
534     if (!builder.Valid()) {
535         return device->WriteFail("Could not open super partition");
536     }
537 
538     auto partition = builder->FindPartition(partition_name);
539     if (!partition) {
540         return device->WriteFail("Partition does not exist");
541     }
542 
543     // Remove the updated flag to cancel any snapshots.
544     uint32_t attrs = partition->attributes();
545     partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
546 
547     if (!builder->ResizePartition(partition, partition_size)) {
548         return device->WriteFail("Not enough space to resize partition");
549     }
550     if (!builder.Write()) {
551         return device->WriteFail("Failed to write partition table");
552     }
553     return device->WriteOkay("Partition resized");
554 }
555 
CancelPartitionSnapshot(FastbootDevice * device,const std::string & partition_name)556 void CancelPartitionSnapshot(FastbootDevice* device, const std::string& partition_name) {
557     PartitionBuilder builder(device, partition_name);
558     if (!builder.Valid()) return;
559 
560     auto partition = builder->FindPartition(partition_name);
561     if (!partition) return;
562 
563     // Remove the updated flag to cancel any snapshots.
564     uint32_t attrs = partition->attributes();
565     partition->set_attributes(attrs & ~LP_PARTITION_ATTR_UPDATED);
566 
567     builder.Write();
568 }
569 
FlashHandler(FastbootDevice * device,const std::vector<std::string> & args)570 bool FlashHandler(FastbootDevice* device, const std::vector<std::string>& args) {
571     if (args.size() < 2) {
572         return device->WriteStatus(FastbootResult::FAIL, "Invalid arguments");
573     }
574 
575     if (GetDeviceLockStatus()) {
576         return device->WriteStatus(FastbootResult::FAIL,
577                                    "Flashing is not allowed on locked devices");
578     }
579 
580     const auto& partition_name = args[1];
581     if (IsProtectedPartitionDuringMerge(device, partition_name)) {
582         auto message = "Cannot flash " + partition_name + " while a snapshot update is in progress";
583         return device->WriteFail(message);
584     }
585 
586     if (LogicalPartitionExists(device, partition_name)) {
587         CancelPartitionSnapshot(device, partition_name);
588     }
589 
590     int ret = Flash(device, partition_name);
591     if (ret < 0) {
592         return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
593     }
594     return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
595 }
596 
UpdateSuperHandler(FastbootDevice * device,const std::vector<std::string> & args)597 bool UpdateSuperHandler(FastbootDevice* device, const std::vector<std::string>& args) {
598     if (args.size() < 2) {
599         return device->WriteFail("Invalid arguments");
600     }
601 
602     if (GetDeviceLockStatus()) {
603         return device->WriteStatus(FastbootResult::FAIL, "Command not available on locked devices");
604     }
605 
606     bool wipe = (args.size() >= 3 && args[2] == "wipe");
607     return UpdateSuper(device, args[1], wipe);
608 }
609 
GsiHandler(FastbootDevice * device,const std::vector<std::string> & args)610 bool GsiHandler(FastbootDevice* device, const std::vector<std::string>& args) {
611     if (args.size() != 2) {
612         return device->WriteFail("Invalid arguments");
613     }
614 
615     AutoMountMetadata mount_metadata;
616     if (!mount_metadata) {
617         return device->WriteFail("Could not find GSI install");
618     }
619 
620     if (!android::gsi::IsGsiInstalled()) {
621         return device->WriteStatus(FastbootResult::FAIL, "No GSI is installed");
622     }
623 
624     if (args[1] == "wipe") {
625         if (!android::gsi::UninstallGsi()) {
626             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
627         }
628     } else if (args[1] == "disable") {
629         if (!android::gsi::DisableGsi()) {
630             return device->WriteStatus(FastbootResult::FAIL, strerror(errno));
631         }
632     }
633     return device->WriteStatus(FastbootResult::OKAY, "Success");
634 }
635 
SnapshotUpdateHandler(FastbootDevice * device,const std::vector<std::string> & args)636 bool SnapshotUpdateHandler(FastbootDevice* device, const std::vector<std::string>& args) {
637     // Note that we use the HAL rather than mounting /metadata, since we want
638     // our results to match the bootloader.
639     auto hal = device->boot1_1();
640     if (!hal) return device->WriteFail("Not supported");
641 
642     // If no arguments, return the same thing as a getvar. Note that we get the
643     // HAL first so we can return "not supported" before we return the less
644     // specific error message below.
645     if (args.size() < 2 || args[1].empty()) {
646         std::string message;
647         if (!GetSnapshotUpdateStatus(device, {}, &message)) {
648             return device->WriteFail("Could not determine update status");
649         }
650         device->WriteInfo(message);
651         return device->WriteOkay("");
652     }
653 
654     MergeStatus status = hal->getSnapshotMergeStatus();
655 
656     if (args.size() != 2) {
657         return device->WriteFail("Invalid arguments");
658     }
659     if (args[1] == "cancel") {
660         switch (status) {
661             case MergeStatus::SNAPSHOTTED:
662             case MergeStatus::MERGING:
663                 hal->setSnapshotMergeStatus(MergeStatus::CANCELLED);
664                 break;
665             default:
666                 break;
667         }
668     } else if (args[1] == "merge") {
669         if (status != MergeStatus::MERGING) {
670             return device->WriteFail("No snapshot merge is in progress");
671         }
672 
673         auto sm = SnapshotManager::NewForFirstStageMount();
674         if (!sm) {
675             return device->WriteFail("Unable to create SnapshotManager");
676         }
677         if (!sm->FinishMergeInRecovery()) {
678             return device->WriteFail("Unable to finish snapshot merge");
679         }
680     } else {
681         return device->WriteFail("Invalid parameter to snapshot-update");
682     }
683     return device->WriteStatus(FastbootResult::OKAY, "Success");
684 }
685