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