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