BacktraceCurrent.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. * Copyright (C) 2013 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. #define _GNU_SOURCE 1
  17. #include <errno.h>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <sys/param.h>
  21. #include <sys/ptrace.h>
  22. #include <sys/types.h>
  23. #include <ucontext.h>
  24. #include <unistd.h>
  25. #include <stdlib.h>
  26. #include <string>
  27. #include <android-base/threads.h>
  28. #include <backtrace/Backtrace.h>
  29. #include <backtrace/BacktraceMap.h>
  30. #include "BacktraceAsyncSafeLog.h"
  31. #include "BacktraceCurrent.h"
  32. #include "ThreadEntry.h"
  33. bool BacktraceCurrent::ReadWord(uint64_t ptr, word_t* out_value) {
  34. if (!VerifyReadWordArgs(ptr, out_value)) {
  35. return false;
  36. }
  37. backtrace_map_t map;
  38. FillInMap(ptr, &map);
  39. if (BacktraceMap::IsValid(map) && map.flags & PROT_READ) {
  40. *out_value = *reinterpret_cast<word_t*>(ptr);
  41. return true;
  42. } else {
  43. BACK_ASYNC_SAFE_LOGW("pointer %p not in a readable map", reinterpret_cast<void*>(ptr));
  44. *out_value = static_cast<word_t>(-1);
  45. return false;
  46. }
  47. }
  48. size_t BacktraceCurrent::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
  49. backtrace_map_t map;
  50. FillInMap(addr, &map);
  51. if (!BacktraceMap::IsValid(map) || !(map.flags & PROT_READ)) {
  52. return 0;
  53. }
  54. bytes = MIN(map.end - addr, bytes);
  55. memcpy(buffer, reinterpret_cast<uint8_t*>(addr), bytes);
  56. return bytes;
  57. }
  58. bool BacktraceCurrent::Unwind(size_t num_ignore_frames, void* ucontext) {
  59. if (GetMap() == nullptr) {
  60. // Without a map object, we can't do anything.
  61. error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
  62. return false;
  63. }
  64. error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
  65. if (ucontext) {
  66. return UnwindFromContext(num_ignore_frames, ucontext);
  67. }
  68. if (Tid() != static_cast<pid_t>(android::base::GetThreadId())) {
  69. return UnwindThread(num_ignore_frames);
  70. }
  71. return UnwindFromContext(num_ignore_frames, nullptr);
  72. }
  73. bool BacktraceCurrent::DiscardFrame(const backtrace_frame_data_t& frame) {
  74. if (BacktraceMap::IsValid(frame.map)) {
  75. const std::string library = basename(frame.map.name.c_str());
  76. if (library == "libunwind.so" || library == "libbacktrace.so") {
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. static pthread_mutex_t g_sigaction_mutex = PTHREAD_MUTEX_INITIALIZER;
  83. // Since errno is stored per thread, changing it in the signal handler
  84. // modifies the value on the thread in which the signal handler executes.
  85. // If a signal occurs between a call and an errno check, it's possible
  86. // to get the errno set here. Always save and restore it just in case
  87. // code would modify it.
  88. class ErrnoRestorer {
  89. public:
  90. ErrnoRestorer() : saved_errno_(errno) {}
  91. ~ErrnoRestorer() {
  92. errno = saved_errno_;
  93. }
  94. private:
  95. int saved_errno_;
  96. };
  97. static void SignalLogOnly(int, siginfo_t*, void*) {
  98. ErrnoRestorer restore;
  99. BACK_ASYNC_SAFE_LOGE("pid %d, tid %d: Received a spurious signal %d\n", getpid(),
  100. static_cast<int>(android::base::GetThreadId()), THREAD_SIGNAL);
  101. }
  102. static void SignalHandler(int, siginfo_t*, void* sigcontext) {
  103. ErrnoRestorer restore;
  104. ThreadEntry* entry = ThreadEntry::Get(getpid(), android::base::GetThreadId(), false);
  105. if (!entry) {
  106. BACK_ASYNC_SAFE_LOGE("pid %d, tid %d entry not found", getpid(),
  107. static_cast<int>(android::base::GetThreadId()));
  108. return;
  109. }
  110. entry->CopyUcontextFromSigcontext(sigcontext);
  111. // Indicate the ucontext is now valid.
  112. entry->Wake();
  113. // Pause the thread until the unwind is complete. This avoids having
  114. // the thread run ahead causing problems.
  115. // The number indicates that we are waiting for the second Wake() call
  116. // overall which is made by the thread requesting an unwind.
  117. if (entry->Wait(2)) {
  118. // Do not remove the entry here because that can result in a deadlock
  119. // if the code cannot properly send a signal to the thread under test.
  120. entry->Wake();
  121. } else {
  122. // At this point, it is possible that entry has been freed, so just exit.
  123. BACK_ASYNC_SAFE_LOGE("Timed out waiting for unwind thread to indicate it completed.");
  124. }
  125. }
  126. bool BacktraceCurrent::UnwindThread(size_t num_ignore_frames) {
  127. // Prevent multiple threads trying to set the trigger action on different
  128. // threads at the same time.
  129. pthread_mutex_lock(&g_sigaction_mutex);
  130. ThreadEntry* entry = ThreadEntry::Get(Pid(), Tid());
  131. entry->Lock();
  132. struct sigaction act, oldact;
  133. memset(&act, 0, sizeof(act));
  134. act.sa_sigaction = SignalHandler;
  135. act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
  136. sigemptyset(&act.sa_mask);
  137. if (sigaction(THREAD_SIGNAL, &act, &oldact) != 0) {
  138. BACK_ASYNC_SAFE_LOGE("sigaction failed: %s", strerror(errno));
  139. ThreadEntry::Remove(entry);
  140. pthread_mutex_unlock(&g_sigaction_mutex);
  141. error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
  142. return false;
  143. }
  144. if (tgkill(Pid(), Tid(), THREAD_SIGNAL) != 0) {
  145. // Do not emit an error message, this might be expected. Set the
  146. // error and let the caller decide.
  147. if (errno == ESRCH) {
  148. error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
  149. } else {
  150. error_.error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
  151. }
  152. sigaction(THREAD_SIGNAL, &oldact, nullptr);
  153. ThreadEntry::Remove(entry);
  154. pthread_mutex_unlock(&g_sigaction_mutex);
  155. return false;
  156. }
  157. // Wait for the thread to get the ucontext. The number indicates
  158. // that we are waiting for the first Wake() call made by the thread.
  159. bool wait_completed = entry->Wait(1);
  160. if (!wait_completed && oldact.sa_sigaction == nullptr) {
  161. // If the wait failed, it could be that the signal could not be delivered
  162. // within the timeout. Add a signal handler that's simply going to log
  163. // something so that we don't crash if the signal eventually gets
  164. // delivered. Only do this if there isn't already an action set up.
  165. memset(&act, 0, sizeof(act));
  166. act.sa_sigaction = SignalLogOnly;
  167. act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
  168. sigemptyset(&act.sa_mask);
  169. sigaction(THREAD_SIGNAL, &act, nullptr);
  170. } else {
  171. sigaction(THREAD_SIGNAL, &oldact, nullptr);
  172. }
  173. // After the thread has received the signal, allow other unwinders to
  174. // continue.
  175. pthread_mutex_unlock(&g_sigaction_mutex);
  176. bool unwind_done = false;
  177. if (wait_completed) {
  178. unwind_done = UnwindFromContext(num_ignore_frames, entry->GetUcontext());
  179. // Tell the signal handler to exit and release the entry.
  180. entry->Wake();
  181. // Wait for the thread to indicate it is done with the ThreadEntry.
  182. if (!entry->Wait(3)) {
  183. // Send a warning, but do not mark as a failure to unwind.
  184. BACK_ASYNC_SAFE_LOGW("Timed out waiting for signal handler to indicate it finished.");
  185. }
  186. } else {
  187. // Check to see if the thread has disappeared.
  188. if (tgkill(Pid(), Tid(), 0) == -1 && errno == ESRCH) {
  189. error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
  190. } else {
  191. error_.error_code = BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT;
  192. BACK_ASYNC_SAFE_LOGE("Timed out waiting for signal handler to get ucontext data.");
  193. }
  194. }
  195. ThreadEntry::Remove(entry);
  196. return unwind_done;
  197. }