• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "android-base/stringprintf.h"
31 #include "arch/instruction_set.h"
32 #include "base/time_utils.h"
33 #include "base/unix_file/fd_file.h"
34 #include "class_linker.h"
35 #include "gc/heap.h"
36 #include "jit/profile_saver.h"
37 #include "os.h"
38 #include "runtime.h"
39 #include "scoped_thread_state_change-inl.h"
40 #include "signal_set.h"
41 #include "thread.h"
42 #include "thread_list.h"
43 #include "utils.h"
44 
45 #if defined(ART_TARGET_ANDROID)
46 #include "tombstoned/tombstoned.h"
47 #endif
48 
49 namespace art {
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 (ReadFileToString("/proc/self/cmdline", &current_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(const std::string & stack_trace_file,bool use_tombstoned_stack_trace_fd)73 SignalCatcher::SignalCatcher(const std::string& stack_trace_file,
74                              bool use_tombstoned_stack_trace_fd)
75     : stack_trace_file_(stack_trace_file),
76       use_tombstoned_stack_trace_fd_(use_tombstoned_stack_trace_fd),
77       lock_("SignalCatcher lock"),
78       cond_("SignalCatcher::cond_", lock_),
79       thread_(nullptr) {
80 #if !defined(ART_TARGET_ANDROID)
81   // We're not running on Android, so we can't communicate with tombstoned
82   // to ask for an open file.
83   CHECK(!use_tombstoned_stack_trace_fd_);
84 #endif
85 
86   SetHaltFlag(false);
87 
88   // Create a raw pthread; its start routine will attach to the runtime.
89   CHECK_PTHREAD_CALL(pthread_create, (&pthread_, nullptr, &Run, this), "signal catcher thread");
90 
91   Thread* self = Thread::Current();
92   MutexLock mu(self, lock_);
93   while (thread_ == nullptr) {
94     cond_.Wait(self);
95   }
96 }
97 
~SignalCatcher()98 SignalCatcher::~SignalCatcher() {
99   // Since we know the thread is just sitting around waiting for signals
100   // to arrive, send it one.
101   SetHaltFlag(true);
102   CHECK_PTHREAD_CALL(pthread_kill, (pthread_, SIGQUIT), "signal catcher shutdown");
103   CHECK_PTHREAD_CALL(pthread_join, (pthread_, nullptr), "signal catcher shutdown");
104 }
105 
SetHaltFlag(bool new_value)106 void SignalCatcher::SetHaltFlag(bool new_value) {
107   MutexLock mu(Thread::Current(), lock_);
108   halt_ = new_value;
109 }
110 
ShouldHalt()111 bool SignalCatcher::ShouldHalt() {
112   MutexLock mu(Thread::Current(), lock_);
113   return halt_;
114 }
115 
OpenStackTraceFile(android::base::unique_fd * tombstone_fd,android::base::unique_fd * output_fd)116 bool SignalCatcher::OpenStackTraceFile(android::base::unique_fd* tombstone_fd,
117                                        android::base::unique_fd* output_fd) {
118   if (use_tombstoned_stack_trace_fd_) {
119 #if defined(ART_TARGET_ANDROID)
120     return tombstoned_connect(getpid(), tombstone_fd, output_fd, kDebuggerdJavaBacktrace);
121 #else
122     UNUSED(tombstone_fd);
123     UNUSED(output_fd);
124 #endif
125   }
126 
127   // The runtime is not configured to dump traces to a file, will LOG(INFO)
128   // instead.
129   if (stack_trace_file_.empty()) {
130     return false;
131   }
132 
133   int fd = open(stack_trace_file_.c_str(), O_APPEND | O_CREAT | O_WRONLY, 0666);
134   if (fd == -1) {
135       PLOG(ERROR) << "Unable to open stack trace file '" << stack_trace_file_ << "'";
136       return false;
137   }
138 
139   output_fd->reset(fd);
140   return true;
141 }
142 
Output(const std::string & s)143 void SignalCatcher::Output(const std::string& s) {
144   android::base::unique_fd tombstone_fd;
145   android::base::unique_fd output_fd;
146   if (!OpenStackTraceFile(&tombstone_fd, &output_fd)) {
147     LOG(INFO) << s;
148     return;
149   }
150 
151   ScopedThreadStateChange tsc(Thread::Current(), kWaitingForSignalCatcherOutput);
152 
153   std::unique_ptr<File> file(new File(output_fd.release(), true /* check_usage */));
154   bool success = file->WriteFully(s.data(), s.size());
155   if (success) {
156     success = file->FlushCloseOrErase() == 0;
157   } else {
158     file->Erase();
159   }
160 
161   const std::string output_path_msg = (use_tombstoned_stack_trace_fd_) ?
162       "[tombstoned]" : stack_trace_file_;
163 
164   if (success) {
165     LOG(INFO) << "Wrote stack traces to '" << output_path_msg << "'";
166   } else {
167     PLOG(ERROR) << "Failed to write stack traces to '" << output_path_msg << "'";
168   }
169 
170 #if defined(ART_TARGET_ANDROID)
171   if (use_tombstoned_stack_trace_fd_ && !tombstoned_notify_completion(tombstone_fd)) {
172     PLOG(WARNING) << "Unable to notify tombstoned of dump completion";
173   }
174 #endif
175 }
176 
HandleSigQuit()177 void SignalCatcher::HandleSigQuit() {
178   Runtime* runtime = Runtime::Current();
179   std::ostringstream os;
180   os << "\n"
181       << "----- pid " << getpid() << " at " << GetIsoDate() << " -----\n";
182 
183   DumpCmdLine(os);
184 
185   // Note: The strings "Build fingerprint:" and "ABI:" are chosen to match the format used by
186   // debuggerd. This allows, for example, the stack tool to work.
187   std::string fingerprint = runtime->GetFingerprint();
188   os << "Build fingerprint: '" << (fingerprint.empty() ? "unknown" : fingerprint) << "'\n";
189   os << "ABI: '" << GetInstructionSetString(runtime->GetInstructionSet()) << "'\n";
190 
191   os << "Build type: " << (kIsDebugBuild ? "debug" : "optimized") << "\n";
192 
193   runtime->DumpForSigQuit(os);
194 
195   if ((false)) {
196     std::string maps;
197     if (ReadFileToString("/proc/self/maps", &maps)) {
198       os << "/proc/self/maps:\n" << maps;
199     }
200   }
201   os << "----- end " << getpid() << " -----\n";
202   Output(os.str());
203 }
204 
HandleSigUsr1()205 void SignalCatcher::HandleSigUsr1() {
206   LOG(INFO) << "SIGUSR1 forcing GC (no HPROF) and profile save";
207   Runtime::Current()->GetHeap()->CollectGarbage(false);
208   ProfileSaver::ForceProcessProfiles();
209 }
210 
WaitForSignal(Thread * self,SignalSet & signals)211 int SignalCatcher::WaitForSignal(Thread* self, SignalSet& signals) {
212   ScopedThreadStateChange tsc(self, kWaitingInMainSignalCatcherLoop);
213 
214   // Signals for sigwait() must be blocked but not ignored.  We
215   // block signals like SIGQUIT for all threads, so the condition
216   // is met.  When the signal hits, we wake up, without any signal
217   // handlers being invoked.
218   int signal_number = signals.Wait();
219   if (!ShouldHalt()) {
220     // Let the user know we got the signal, just in case the system's too screwed for us to
221     // actually do what they want us to do...
222     LOG(INFO) << *self << ": reacting to signal " << signal_number;
223 
224     // If anyone's holding locks (which might prevent us from getting back into state Runnable), say so...
225     Runtime::Current()->DumpLockHolders(LOG_STREAM(INFO));
226   }
227 
228   return signal_number;
229 }
230 
Run(void * arg)231 void* SignalCatcher::Run(void* arg) {
232   SignalCatcher* signal_catcher = reinterpret_cast<SignalCatcher*>(arg);
233   CHECK(signal_catcher != nullptr);
234 
235   Runtime* runtime = Runtime::Current();
236   CHECK(runtime->AttachCurrentThread("Signal Catcher", true, runtime->GetSystemThreadGroup(),
237                                      !runtime->IsAotCompiler()));
238 
239   Thread* self = Thread::Current();
240   DCHECK_NE(self->GetState(), kRunnable);
241   {
242     MutexLock mu(self, signal_catcher->lock_);
243     signal_catcher->thread_ = self;
244     signal_catcher->cond_.Broadcast(self);
245   }
246 
247   // Set up mask with signals we want to handle.
248   SignalSet signals;
249   signals.Add(SIGQUIT);
250   signals.Add(SIGUSR1);
251 
252   while (true) {
253     int signal_number = signal_catcher->WaitForSignal(self, signals);
254     if (signal_catcher->ShouldHalt()) {
255       runtime->DetachCurrentThread();
256       return nullptr;
257     }
258 
259     switch (signal_number) {
260     case SIGQUIT:
261       signal_catcher->HandleSigQuit();
262       break;
263     case SIGUSR1:
264       signal_catcher->HandleSigUsr1();
265       break;
266     default:
267       LOG(ERROR) << "Unexpected signal %d" << signal_number;
268       break;
269     }
270   }
271 }
272 
273 }  // namespace art
274