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 "fault_handler.h"
18 
19 #include <setjmp.h>
20 #include <sys/mman.h>
21 #include <sys/ucontext.h>
22 
23 #include "art_method-inl.h"
24 #include "base/safe_copy.h"
25 #include "base/stl_util.h"
26 #include "mirror/class.h"
27 #include "mirror/object_reference.h"
28 #include "oat_quick_method_header.h"
29 #include "sigchain.h"
30 #include "thread-inl.h"
31 #include "verify_object-inl.h"
32 
33 namespace art {
34 // Static fault manger object accessed by signal handler.
35 FaultManager fault_manager;
36 
art_sigsegv_fault()37 extern "C" __attribute__((visibility("default"))) void art_sigsegv_fault() {
38   // Set a breakpoint here to be informed when a SIGSEGV is unhandled by ART.
39   VLOG(signals)<< "Caught unknown SIGSEGV in ART fault handler - chaining to next handler.";
40 }
41 
42 // Signal handler called on SIGSEGV.
art_fault_handler(int sig,siginfo_t * info,void * context)43 static bool art_fault_handler(int sig, siginfo_t* info, void* context) {
44   return fault_manager.HandleFault(sig, info, context);
45 }
46 
47 #if defined(__linux__)
48 
49 // Change to verify the safe implementations against the original ones.
50 constexpr bool kVerifySafeImpls = false;
51 
52 // Provide implementations of ArtMethod::GetDeclaringClass and VerifyClassClass that use SafeCopy
53 // to safely dereference pointers which are potentially garbage.
54 // Only available on Linux due to availability of SafeCopy.
55 
SafeGetDeclaringClass(ArtMethod * method)56 static mirror::Class* SafeGetDeclaringClass(ArtMethod* method)
57     REQUIRES_SHARED(Locks::mutator_lock_) {
58   char* method_declaring_class =
59       reinterpret_cast<char*>(method) + ArtMethod::DeclaringClassOffset().SizeValue();
60 
61   // ArtMethod::declaring_class_ is a GcRoot<mirror::Class>.
62   // Read it out into as a CompressedReference directly for simplicity's sake.
63   mirror::CompressedReference<mirror::Class> cls;
64   ssize_t rc = SafeCopy(&cls, method_declaring_class, sizeof(cls));
65   CHECK_NE(-1, rc);
66 
67   if (kVerifySafeImpls) {
68     mirror::Class* actual_class = method->GetDeclaringClassUnchecked<kWithoutReadBarrier>();
69     CHECK_EQ(actual_class, cls.AsMirrorPtr());
70   }
71 
72   if (rc != sizeof(cls)) {
73     return nullptr;
74   }
75 
76   return cls.AsMirrorPtr();
77 }
78 
SafeGetClass(mirror::Object * obj)79 static mirror::Class* SafeGetClass(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
80   char* obj_cls = reinterpret_cast<char*>(obj) + mirror::Object::ClassOffset().SizeValue();
81 
82   mirror::HeapReference<mirror::Class> cls =
83       mirror::HeapReference<mirror::Class>::FromMirrorPtr(nullptr);
84   ssize_t rc = SafeCopy(&cls, obj_cls, sizeof(cls));
85   CHECK_NE(-1, rc);
86 
87   if (kVerifySafeImpls) {
88     mirror::Class* actual_class = obj->GetClass<kVerifyNone>();
89     CHECK_EQ(actual_class, cls.AsMirrorPtr());
90   }
91 
92   if (rc != sizeof(cls)) {
93     return nullptr;
94   }
95 
96   return cls.AsMirrorPtr();
97 }
98 
SafeVerifyClassClass(mirror::Class * cls)99 static bool SafeVerifyClassClass(mirror::Class* cls) REQUIRES_SHARED(Locks::mutator_lock_) {
100   mirror::Class* c_c = SafeGetClass(cls);
101   bool result = c_c != nullptr && c_c == SafeGetClass(c_c);
102 
103   if (kVerifySafeImpls) {
104     CHECK_EQ(VerifyClassClass(cls), result);
105   }
106 
107   return result;
108 }
109 
110 #else
111 
SafeGetDeclaringClass(ArtMethod * method_obj)112 static mirror::Class* SafeGetDeclaringClass(ArtMethod* method_obj)
113     REQUIRES_SHARED(Locks::mutator_lock_) {
114   return method_obj->GetDeclaringClassUnchecked<kWithoutReadBarrier>();
115 }
116 
SafeVerifyClassClass(mirror::Class * cls)117 static bool SafeVerifyClassClass(mirror::Class* cls) REQUIRES_SHARED(Locks::mutator_lock_) {
118   return VerifyClassClass(cls);
119 }
120 #endif
121 
122 
FaultManager()123 FaultManager::FaultManager() : initialized_(false) {
124   sigaction(SIGSEGV, nullptr, &oldaction_);
125 }
126 
~FaultManager()127 FaultManager::~FaultManager() {
128 }
129 
Init()130 void FaultManager::Init() {
131   CHECK(!initialized_);
132   sigset_t mask;
133   sigfillset(&mask);
134   sigdelset(&mask, SIGABRT);
135   sigdelset(&mask, SIGBUS);
136   sigdelset(&mask, SIGFPE);
137   sigdelset(&mask, SIGILL);
138   sigdelset(&mask, SIGSEGV);
139 
140   SigchainAction sa = {
141     .sc_sigaction = art_fault_handler,
142     .sc_mask = mask,
143     .sc_flags = 0UL,
144   };
145 
146   AddSpecialSignalHandlerFn(SIGSEGV, &sa);
147   initialized_ = true;
148 }
149 
Release()150 void FaultManager::Release() {
151   if (initialized_) {
152     RemoveSpecialSignalHandlerFn(SIGSEGV, art_fault_handler);
153     initialized_ = false;
154   }
155 }
156 
Shutdown()157 void FaultManager::Shutdown() {
158   if (initialized_) {
159     Release();
160 
161     // Free all handlers.
162     STLDeleteElements(&generated_code_handlers_);
163     STLDeleteElements(&other_handlers_);
164   }
165 }
166 
HandleFaultByOtherHandlers(int sig,siginfo_t * info,void * context)167 bool FaultManager::HandleFaultByOtherHandlers(int sig, siginfo_t* info, void* context) {
168   if (other_handlers_.empty()) {
169     return false;
170   }
171 
172   Thread* self = Thread::Current();
173 
174   DCHECK(self != nullptr);
175   DCHECK(Runtime::Current() != nullptr);
176   DCHECK(Runtime::Current()->IsStarted());
177   for (const auto& handler : other_handlers_) {
178     if (handler->Action(sig, info, context)) {
179       return true;
180     }
181   }
182   return false;
183 }
184 
HandleFault(int sig,siginfo_t * info,void * context)185 bool FaultManager::HandleFault(int sig, siginfo_t* info, void* context) {
186   VLOG(signals) << "Handling fault";
187 
188 #ifdef TEST_NESTED_SIGNAL
189   // Simulate a crash in a handler.
190   raise(SIGSEGV);
191 #endif
192 
193   if (IsInGeneratedCode(info, context, true)) {
194     VLOG(signals) << "in generated code, looking for handler";
195     for (const auto& handler : generated_code_handlers_) {
196       VLOG(signals) << "invoking Action on handler " << handler;
197       if (handler->Action(sig, info, context)) {
198         // We have handled a signal so it's time to return from the
199         // signal handler to the appropriate place.
200         return true;
201       }
202     }
203 
204     // We hit a signal we didn't handle.  This might be something for which
205     // we can give more information about so call all registered handlers to
206     // see if it is.
207     if (HandleFaultByOtherHandlers(sig, info, context)) {
208       return true;
209     }
210   }
211 
212   // Set a breakpoint in this function to catch unhandled signals.
213   art_sigsegv_fault();
214   return false;
215 }
216 
AddHandler(FaultHandler * handler,bool generated_code)217 void FaultManager::AddHandler(FaultHandler* handler, bool generated_code) {
218   DCHECK(initialized_);
219   if (generated_code) {
220     generated_code_handlers_.push_back(handler);
221   } else {
222     other_handlers_.push_back(handler);
223   }
224 }
225 
RemoveHandler(FaultHandler * handler)226 void FaultManager::RemoveHandler(FaultHandler* handler) {
227   auto it = std::find(generated_code_handlers_.begin(), generated_code_handlers_.end(), handler);
228   if (it != generated_code_handlers_.end()) {
229     generated_code_handlers_.erase(it);
230     return;
231   }
232   auto it2 = std::find(other_handlers_.begin(), other_handlers_.end(), handler);
233   if (it2 != other_handlers_.end()) {
234     other_handlers_.erase(it);
235     return;
236   }
237   LOG(FATAL) << "Attempted to remove non existent handler " << handler;
238 }
239 
240 // This function is called within the signal handler.  It checks that
241 // the mutator_lock is held (shared).  No annotalysis is done.
IsInGeneratedCode(siginfo_t * siginfo,void * context,bool check_dex_pc)242 bool FaultManager::IsInGeneratedCode(siginfo_t* siginfo, void* context, bool check_dex_pc) {
243   // We can only be running Java code in the current thread if it
244   // is in Runnable state.
245   VLOG(signals) << "Checking for generated code";
246   Thread* thread = Thread::Current();
247   if (thread == nullptr) {
248     VLOG(signals) << "no current thread";
249     return false;
250   }
251 
252   ThreadState state = thread->GetState();
253   if (state != kRunnable) {
254     VLOG(signals) << "not runnable";
255     return false;
256   }
257 
258   // Current thread is runnable.
259   // Make sure it has the mutator lock.
260   if (!Locks::mutator_lock_->IsSharedHeld(thread)) {
261     VLOG(signals) << "no lock";
262     return false;
263   }
264 
265   ArtMethod* method_obj = nullptr;
266   uintptr_t return_pc = 0;
267   uintptr_t sp = 0;
268 
269   // Get the architecture specific method address and return address.  These
270   // are in architecture specific files in arch/<arch>/fault_handler_<arch>.
271   GetMethodAndReturnPcAndSp(siginfo, context, &method_obj, &return_pc, &sp);
272 
273   // If we don't have a potential method, we're outta here.
274   VLOG(signals) << "potential method: " << method_obj;
275   // TODO: Check linear alloc and image.
276   DCHECK_ALIGNED(ArtMethod::Size(kRuntimePointerSize), sizeof(void*))
277       << "ArtMethod is not pointer aligned";
278   if (method_obj == nullptr || !IsAligned<sizeof(void*)>(method_obj)) {
279     VLOG(signals) << "no method";
280     return false;
281   }
282 
283   // Verify that the potential method is indeed a method.
284   // TODO: check the GC maps to make sure it's an object.
285   // Check that the class pointer inside the object is not null and is aligned.
286   // No read barrier because method_obj may not be a real object.
287   mirror::Class* cls = SafeGetDeclaringClass(method_obj);
288   if (cls == nullptr) {
289     VLOG(signals) << "not a class";
290     return false;
291   }
292 
293   if (!IsAligned<kObjectAlignment>(cls)) {
294     VLOG(signals) << "not aligned";
295     return false;
296   }
297 
298   if (!SafeVerifyClassClass(cls)) {
299     VLOG(signals) << "not a class class";
300     return false;
301   }
302 
303   const OatQuickMethodHeader* method_header = method_obj->GetOatQuickMethodHeader(return_pc);
304 
305   // We can be certain that this is a method now.  Check if we have a GC map
306   // at the return PC address.
307   if (true || kIsDebugBuild) {
308     VLOG(signals) << "looking for dex pc for return pc " << std::hex << return_pc;
309     uint32_t sought_offset = return_pc -
310         reinterpret_cast<uintptr_t>(method_header->GetEntryPoint());
311     VLOG(signals) << "pc offset: " << std::hex << sought_offset;
312   }
313   uint32_t dexpc = method_header->ToDexPc(method_obj, return_pc, false);
314   VLOG(signals) << "dexpc: " << dexpc;
315   return !check_dex_pc || dexpc != DexFile::kDexNoIndex;
316 }
317 
FaultHandler(FaultManager * manager)318 FaultHandler::FaultHandler(FaultManager* manager) : manager_(manager) {
319 }
320 
321 //
322 // Null pointer fault handler
323 //
NullPointerHandler(FaultManager * manager)324 NullPointerHandler::NullPointerHandler(FaultManager* manager) : FaultHandler(manager) {
325   manager_->AddHandler(this, true);
326 }
327 
328 //
329 // Suspension fault handler
330 //
SuspensionHandler(FaultManager * manager)331 SuspensionHandler::SuspensionHandler(FaultManager* manager) : FaultHandler(manager) {
332   manager_->AddHandler(this, true);
333 }
334 
335 //
336 // Stack overflow fault handler
337 //
StackOverflowHandler(FaultManager * manager)338 StackOverflowHandler::StackOverflowHandler(FaultManager* manager) : FaultHandler(manager) {
339   manager_->AddHandler(this, true);
340 }
341 
342 //
343 // Stack trace handler, used to help get a stack trace from SIGSEGV inside of compiled code.
344 //
JavaStackTraceHandler(FaultManager * manager)345 JavaStackTraceHandler::JavaStackTraceHandler(FaultManager* manager) : FaultHandler(manager) {
346   manager_->AddHandler(this, false);
347 }
348 
Action(int sig ATTRIBUTE_UNUSED,siginfo_t * siginfo,void * context)349 bool JavaStackTraceHandler::Action(int sig ATTRIBUTE_UNUSED, siginfo_t* siginfo, void* context) {
350   // Make sure that we are in the generated code, but we may not have a dex pc.
351   bool in_generated_code = manager_->IsInGeneratedCode(siginfo, context, false);
352   if (in_generated_code) {
353     LOG(ERROR) << "Dumping java stack trace for crash in generated code";
354     ArtMethod* method = nullptr;
355     uintptr_t return_pc = 0;
356     uintptr_t sp = 0;
357     Thread* self = Thread::Current();
358 
359     manager_->GetMethodAndReturnPcAndSp(siginfo, context, &method, &return_pc, &sp);
360     // Inside of generated code, sp[0] is the method, so sp is the frame.
361     self->SetTopOfStack(reinterpret_cast<ArtMethod**>(sp));
362     self->DumpJavaStack(LOG_STREAM(ERROR));
363   }
364 
365   return false;  // Return false since we want to propagate the fault to the main signal handler.
366 }
367 
368 }   // namespace art
369