• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 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 #include <stddef.h>
17 #include <stdint.h>
18 #include <unistd.h>
19 
20 #include <string>
21 #include <vector>
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/parseint.h>
26 #include <bootloader_message/bootloader_message.h>
27 #include <cutils/android_reboot.h>
28 
29 #include "reboot_utils.h"
30 
31 namespace android {
32 namespace init {
33 
RequestTradeInModeWipeIfNeeded()34 void RequestTradeInModeWipeIfNeeded() {
35     static constexpr const char* kWipeIndicator = "/metadata/tradeinmode/wipe";
36     static constexpr size_t kWipeAttempts = 3;
37 
38     if (access(kWipeIndicator, R_OK) == -1) {
39         return;
40     }
41 
42     // Write a counter to the wipe indicator, to try and prevent boot loops if
43     // recovery fails to wipe data.
44     uint32_t counter = 0;
45     std::string contents;
46     if (android::base::ReadFileToString(kWipeIndicator, &contents)) {
47         android::base::ParseUint(contents, &counter);
48         contents = std::to_string(++counter);
49         if (android::base::WriteStringToFile(contents, kWipeIndicator)) {
50             sync();
51         } else {
52             PLOG(ERROR) << "Failed to update " << kWipeIndicator;
53         }
54     } else {
55         PLOG(ERROR) << "Failed to read " << kWipeIndicator;
56     }
57 
58     std::string err;
59     auto misc_device = get_misc_blk_device(&err);
60     if (misc_device.empty()) {
61         LOG(FATAL) << "Could not find misc device: " << err;
62     }
63 
64     // If we've failed to wipe three times, don't include the wipe command. This
65     // will force us to boot into the recovery menu instead where a manual wipe
66     // can be attempted.
67     std::vector<std::string> options;
68     if (counter <= kWipeAttempts) {
69         options.emplace_back("--wipe_data");
70         options.emplace_back("--reason=tradeinmode");
71     }
72     if (!write_bootloader_message(options, &err)) {
73         LOG(FATAL) << "Could not issue wipe: " << err;
74     }
75     RebootSystem(ANDROID_RB_RESTART2, "recovery", "reboot,tradeinmode,wipe");
76 }
77 
78 }  // namespace init
79 }  // namespace android
80