• 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 <sys/capability.h>
18 #include <sys/reboot.h>
19 #include <sys/syscall.h>
20 #include <unistd.h>
21 
22 #include <optional>
23 #include <string>
24 
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/properties.h>
28 #include <android-base/strings.h>
29 #include <cutils/android_reboot.h>
30 #include <unwindstack/AndroidUnwinder.h>
31 
32 #include "capabilities.h"
33 #include "reboot_utils.h"
34 #include "util.h"
35 
36 namespace android {
37 namespace init {
38 
39 static std::string init_fatal_reboot_target = "bootloader";
40 static bool init_fatal_panic = false;
41 
42 // this needs to read the /proc/* files directly because it is called before
43 // ro.boot.* properties are initialized
SetFatalRebootTarget(const std::optional<std::string> & reboot_target)44 void SetFatalRebootTarget(const std::optional<std::string>& reboot_target) {
45     std::string cmdline;
46     android::base::ReadFileToString("/proc/cmdline", &cmdline);
47     cmdline = android::base::Trim(cmdline);
48 
49     const std::string kInitFatalPanicParamString = "androidboot.init_fatal_panic";
50     if (cmdline.find(kInitFatalPanicParamString) == std::string::npos) {
51         init_fatal_panic = false;
52         ImportBootconfig(
53                 [kInitFatalPanicParamString](const std::string& key, const std::string& value) {
54                     if (key == kInitFatalPanicParamString && value == "true") {
55                         init_fatal_panic = true;
56                     }
57                 });
58     } else {
59         const std::string kInitFatalPanicString = kInitFatalPanicParamString + "=true";
60         init_fatal_panic = cmdline.find(kInitFatalPanicString) != std::string::npos;
61     }
62 
63     if (reboot_target) {
64         init_fatal_reboot_target = *reboot_target;
65         return;
66     }
67 
68     const std::string kRebootTargetString = "androidboot.init_fatal_reboot_target";
69     auto start_pos = cmdline.find(kRebootTargetString);
70     if (start_pos == std::string::npos) {
71         ImportBootconfig([kRebootTargetString](const std::string& key, const std::string& value) {
72             if (key == kRebootTargetString) {
73                 init_fatal_reboot_target = value;
74             }
75         });
76         // We already default to bootloader if no setting is provided.
77     } else {
78         const std::string kRebootTargetStringPattern = kRebootTargetString + "=";
79         start_pos += sizeof(kRebootTargetStringPattern) - 1;
80 
81         auto end_pos = cmdline.find(' ', start_pos);
82         // if end_pos isn't found, then we've run off the end, but this is okay as this is the last
83         // entry, and -1 is a valid size for string::substr();
84         auto size = end_pos == std::string::npos ? -1 : end_pos - start_pos;
85         init_fatal_reboot_target = cmdline.substr(start_pos, size);
86     }
87 }
88 
IsRebootCapable()89 bool IsRebootCapable() {
90     if (!CAP_IS_SUPPORTED(CAP_SYS_BOOT)) {
91         PLOG(WARNING) << "CAP_SYS_BOOT is not supported";
92         return true;
93     }
94 
95     ScopedCaps caps(cap_get_proc());
96     if (!caps) {
97         PLOG(WARNING) << "cap_get_proc() failed";
98         return true;
99     }
100 
101     cap_flag_value_t value = CAP_SET;
102     if (cap_get_flag(caps.get(), CAP_SYS_BOOT, CAP_EFFECTIVE, &value) != 0) {
103         PLOG(WARNING) << "cap_get_flag(CAP_SYS_BOOT, EFFECTIVE) failed";
104         return true;
105     }
106     return value == CAP_SET;
107 }
108 
109 void __attribute__((noreturn))
RebootSystem(unsigned int cmd,const std::string & rebootTarget,const std::string & reboot_reason)110 RebootSystem(unsigned int cmd, const std::string& rebootTarget, const std::string& reboot_reason) {
111     LOG(INFO) << "Reboot ending, jumping to kernel";
112 
113     if (!IsRebootCapable()) {
114         // On systems where init does not have the capability of rebooting the
115         // device, just exit cleanly.
116         exit(0);
117     }
118 
119     switch (cmd) {
120         case ANDROID_RB_POWEROFF:
121             reboot(RB_POWER_OFF);
122             break;
123 
124         case ANDROID_RB_RESTART2:
125             syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
126                     LINUX_REBOOT_CMD_RESTART2, rebootTarget.c_str());
127             break;
128 
129         case ANDROID_RB_THERMOFF:
130             if (android::base::GetBoolProperty("ro.thermal_warmreset", false)) {
131                 std::string reason = "shutdown,thermal";
132                 if (!reboot_reason.empty()) reason = reboot_reason;
133 
134                 LOG(INFO) << "Try to trigger a warm reset for thermal shutdown";
135                 syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
136                         LINUX_REBOOT_CMD_RESTART2, reason.c_str());
137             } else {
138                 reboot(RB_POWER_OFF);
139             }
140             break;
141     }
142     // In normal case, reboot should not return.
143     PLOG(ERROR) << "reboot call returned";
144     abort();
145 }
146 
InitFatalReboot(int signal_number)147 void __attribute__((noreturn)) InitFatalReboot(int signal_number) {
148     auto pid = fork();
149 
150     if (pid == -1) {
151         // Couldn't fork, don't even try to backtrace, just reboot.
152         RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
153     } else if (pid == 0) {
154         // Fork a child for safety, since we always want to shut down if something goes wrong, but
155         // its worth trying to get the backtrace, even in the signal handler, since typically it
156         // does work despite not being async-signal-safe.
157         sleep(5);
158         RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
159     }
160 
161     // In the parent, let's try to get a backtrace then shutdown.
162     LOG(ERROR) << __FUNCTION__ << ": signal " << signal_number;
163     unwindstack::AndroidLocalUnwinder unwinder;
164     unwindstack::AndroidUnwinderData data;
165     if (!unwinder.Unwind(data)) {
166         LOG(ERROR) << __FUNCTION__ << ": Failed to unwind callstack: " << data.GetErrorString();
167     }
168     for (const auto& frame : data.frames) {
169         LOG(ERROR) << unwinder.FormatFrame(frame);
170     }
171     if (init_fatal_panic) {
172         LOG(ERROR) << __FUNCTION__ << ": Trigger crash";
173         android::base::WriteStringToFile("c", PROC_SYSRQ);
174         LOG(ERROR) << __FUNCTION__ << ": Sys-Rq failed to crash the system; fallback to exit().";
175         _exit(signal_number);
176     }
177     RebootSystem(ANDROID_RB_RESTART2, init_fatal_reboot_target);
178 }
179 
InstallRebootSignalHandlers()180 void InstallRebootSignalHandlers() {
181     // Instead of panic'ing the kernel as is the default behavior when init crashes,
182     // we prefer to reboot to bootloader on development builds, as this will prevent
183     // boot looping bad configurations and allow both developers and test farms to easily
184     // recover.
185     struct sigaction action;
186     memset(&action, 0, sizeof(action));
187     sigfillset(&action.sa_mask);
188     action.sa_handler = [](int signal) {
189         // These signal handlers are also caught for processes forked from init, however we do not
190         // want them to trigger reboot, so we directly call _exit() for children processes here.
191         if (getpid() != 1) {
192             _exit(signal);
193         }
194 
195         // Calling DoReboot() or LOG(FATAL) is not a good option as this is a signal handler.
196         // RebootSystem uses syscall() which isn't actually async-signal-safe, but our only option
197         // and probably good enough given this is already an error case and only enabled for
198         // development builds.
199         InitFatalReboot(signal);
200     };
201     action.sa_flags = SA_RESTART;
202     sigaction(SIGABRT, &action, nullptr);
203     sigaction(SIGBUS, &action, nullptr);
204     sigaction(SIGFPE, &action, nullptr);
205     sigaction(SIGILL, &action, nullptr);
206     sigaction(SIGSEGV, &action, nullptr);
207 #if defined(SIGSTKFLT)
208     sigaction(SIGSTKFLT, &action, nullptr);
209 #endif
210     sigaction(SIGSYS, &action, nullptr);
211     sigaction(SIGTRAP, &action, nullptr);
212 }
213 
214 }  // namespace init
215 }  // namespace android
216