1 /*
2 * Copyright (C) 2008 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 "signal_catcher.h"
18
19 #include <csignal>
20 #include <cstdlib>
21 #include <fcntl.h>
22 #include <pthread.h>
23 #include <sys/stat.h>
24 #include <sys/time.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27
28 #include <sstream>
29
30 #include <android-base/file.h>
31 #include <android-base/stringprintf.h>
32
33 #include "arch/instruction_set.h"
34 #include "base/logging.h" // For GetCmdLine.
35 #include "base/os.h"
36 #include "base/time_utils.h"
37 #include "base/utils.h"
38 #include "class_linker.h"
39 #include "gc/heap.h"
40 #include "jit/profile_saver.h"
41 #include "palette/palette.h"
42 #include "runtime.h"
43 #include "scoped_thread_state_change-inl.h"
44 #include "signal_set.h"
45 #include "thread.h"
46 #include "thread_list.h"
47
48 namespace art {
49
DumpCmdLine(std::ostream & os)50 static void DumpCmdLine(std::ostream& os) {
51 #if defined(__linux__)
52 // Show the original command line, and the current command line too if it's changed.
53 // On Android, /proc/self/cmdline will have been rewritten to something like "system_server".
54 // Note: The string "Cmd line:" is chosen to match the format used by debuggerd.
55 std::string current_cmd_line;
56 if (android::base::ReadFileToString("/proc/self/cmdline", ¤t_cmd_line)) {
57 current_cmd_line.resize(current_cmd_line.find_last_not_of('\0') + 1); // trim trailing '\0's
58 std::replace(current_cmd_line.begin(), current_cmd_line.end(), '\0', ' ');
59
60 os << "Cmd line: " << current_cmd_line << "\n";
61 const char* stashed_cmd_line = GetCmdLine();
62 if (stashed_cmd_line != nullptr && current_cmd_line != stashed_cmd_line
63 && strcmp(stashed_cmd_line, "<unset>") != 0) {
64 os << "Original command line: " << stashed_cmd_line << "\n";
65 }
66 }
67 #else
68 os << "Cmd line: " << GetCmdLine() << "\n";
69 #endif
70 }
71
SignalCatcher()72 SignalCatcher::SignalCatcher()
73 : lock_("SignalCatcher lock"),
74 cond_("SignalCatcher::cond_", lock_),
75 thread_(nullptr) {
76 SetHaltFlag(false);
77
78 // Create a raw pthread; its start routine will attach to the runtime.
79 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, nullptr, &Run, this), "signal catcher thread");
80
81 Thread* self = Thread::Current();
82 MutexLock mu(self, lock_);
83 while (thread_ == nullptr) {
84 cond_.Wait(self);
85 }
86 }
87
~SignalCatcher()88 SignalCatcher::~SignalCatcher() {
89 // Since we know the thread is just sitting around waiting for signals
90 // to arrive, send it one.
91 SetHaltFlag(true);
92 CHECK_PTHREAD_CALL(pthread_kill, (pthread_, SIGQUIT), "signal catcher shutdown");
93 CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "signal catcher shutdown");
94 }
95
SetHaltFlag(bool new_value)96 void SignalCatcher::SetHaltFlag(bool new_value) {
97 MutexLock mu(Thread::Current(), lock_);
98 halt_ = new_value;
99 }
100
ShouldHalt()101 bool SignalCatcher::ShouldHalt() {
102 MutexLock mu(Thread::Current(), lock_);
103 return halt_;
104 }
105
Output(const std::string & s)106 void SignalCatcher::Output(const std::string& s) {
107 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForSignalCatcherOutput);
108 PaletteStatus status = PaletteWriteCrashThreadStacks(s.data(), s.size());
109 if (status == PaletteStatus::kOkay) {
110 LOG(INFO) << "Wrote stack traces to tombstoned";
111 } else {
112 CHECK(status == PaletteStatus::kFailedCheckLog);
113 LOG(ERROR) << "Failed to write stack traces to tombstoned";
114 }
115 }
116
HandleSigQuit()117 void SignalCatcher::HandleSigQuit() {
118 Runtime* runtime = Runtime::Current();
119 std::ostringstream os;
120 os << "\n"
121 << "----- pid " << getpid() << " at " << GetIsoDate() << " -----\n";
122
123 DumpCmdLine(os);
124
125 // Note: The strings "Build fingerprint:" and "ABI:" are chosen to match the format used by
126 // debuggerd. This allows, for example, the stack tool to work.
127 std::string fingerprint = runtime->GetFingerprint();
128 os << "Build fingerprint: '" << (fingerprint.empty() ? "unknown" : fingerprint) << "'\n";
129 os << "ABI: '" << GetInstructionSetString(runtime->GetInstructionSet()) << "'\n";
130
131 os << "Build type: " << (kIsDebugBuild ? "debug" : "optimized") << "\n";
132
133 runtime->DumpForSigQuit(os);
134
135 if ((false)) {
136 std::string maps;
137 if (android::base::ReadFileToString("/proc/self/maps", &maps)) {
138 os << "/proc/self/maps:\n" << maps;
139 }
140 }
141 os << "----- end " << getpid() << " -----\n";
142 Output(os.str());
143 }
144
HandleSigUsr1()145 void SignalCatcher::HandleSigUsr1() {
146 LOG(INFO) << "SIGUSR1 forcing GC (no HPROF) and profile save";
147 Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ false);
148 ProfileSaver::ForceProcessProfiles();
149 }
150
WaitForSignal(Thread * self,SignalSet & signals)151 int SignalCatcher::WaitForSignal(Thread* self, SignalSet& signals) {
152 ScopedThreadStateChange tsc(self, kWaitingInMainSignalCatcherLoop);
153
154 // Signals for sigwait() must be blocked but not ignored. We
155 // block signals like SIGQUIT for all threads, so the condition
156 // is met. When the signal hits, we wake up, without any signal
157 // handlers being invoked.
158 int signal_number = signals.Wait();
159 if (!ShouldHalt()) {
160 // Let the user know we got the signal, just in case the system's too screwed for us to
161 // actually do what they want us to do...
162 LOG(INFO) << *self << ": reacting to signal " << signal_number;
163
164 // If anyone's holding locks (which might prevent us from getting back into state Runnable), say so...
165 Runtime::Current()->DumpLockHolders(LOG_STREAM(INFO));
166 }
167
168 return signal_number;
169 }
170
Run(void * arg)171 void* SignalCatcher::Run(void* arg) {
172 SignalCatcher* signal_catcher = reinterpret_cast<SignalCatcher*>(arg);
173 CHECK(signal_catcher != nullptr);
174
175 Runtime* runtime = Runtime::Current();
176 CHECK(runtime->AttachCurrentThread("Signal Catcher", true, runtime->GetSystemThreadGroup(),
177 !runtime->IsAotCompiler()));
178
179 Thread* self = Thread::Current();
180 DCHECK_NE(self->GetState(), kRunnable);
181 {
182 MutexLock mu(self, signal_catcher->lock_);
183 signal_catcher->thread_ = self;
184 signal_catcher->cond_.Broadcast(self);
185 }
186
187 // Set up mask with signals we want to handle.
188 SignalSet signals;
189 signals.Add(SIGQUIT);
190 signals.Add(SIGUSR1);
191
192 while (true) {
193 int signal_number = signal_catcher->WaitForSignal(self, signals);
194 if (signal_catcher->ShouldHalt()) {
195 runtime->DetachCurrentThread();
196 return nullptr;
197 }
198
199 switch (signal_number) {
200 case SIGQUIT:
201 signal_catcher->HandleSigQuit();
202 break;
203 case SIGUSR1:
204 signal_catcher->HandleSigUsr1();
205 break;
206 default:
207 LOG(ERROR) << "Unexpected signal %d" << signal_number;
208 break;
209 }
210 }
211 }
212
213 } // namespace art
214