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