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