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