/thirdparty/breakpad/client/linux/handler/exception_handler.cc

http://github.com/tomahawk-player/tomahawk · C++ · 523 lines · 328 code · 65 blank · 130 comment · 58 complexity · 6b51de1e88bd892a94d2cf4e2b085c8a MD5 · raw file

  1. // Copyright (c) 2010 Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // The ExceptionHandler object installs signal handlers for a number of
  30. // signals. We rely on the signal handler running on the thread which crashed
  31. // in order to identify it. This is true of the synchronous signals (SEGV etc),
  32. // but not true of ABRT. Thus, if you send ABRT to yourself in a program which
  33. // uses ExceptionHandler, you need to use tgkill to direct it to the current
  34. // thread.
  35. //
  36. // The signal flow looks like this:
  37. //
  38. // SignalHandler (uses a global stack of ExceptionHandler objects to find
  39. // | one to handle the signal. If the first rejects it, try
  40. // | the second etc...)
  41. // V
  42. // HandleSignal ----------------------------| (clones a new process which
  43. // | | shares an address space with
  44. // (wait for cloned | the crashed process. This
  45. // process) | allows us to ptrace the crashed
  46. // | | process)
  47. // V V
  48. // (set signal handler to ThreadEntry (static function to bounce
  49. // SIG_DFL and rethrow, | back into the object)
  50. // killing the crashed |
  51. // process) V
  52. // DoDump (writes minidump)
  53. // |
  54. // V
  55. // sys_exit
  56. //
  57. // This code is a little fragmented. Different functions of the ExceptionHandler
  58. // class run in a number of different contexts. Some of them run in a normal
  59. // context and are easy to code, others run in a compromised context and the
  60. // restrictions at the top of minidump_writer.cc apply: no libc and use the
  61. // alternative malloc. Each function should have comment above it detailing the
  62. // context which it runs in.
  63. #include "client/linux/handler/exception_handler.h"
  64. #include <errno.h>
  65. #include <fcntl.h>
  66. #include <linux/limits.h>
  67. #include <sched.h>
  68. #include <signal.h>
  69. #include <stdio.h>
  70. #include <sys/mman.h>
  71. #include <sys/prctl.h>
  72. #include <sys/syscall.h>
  73. #include <sys/wait.h>
  74. #include <unistd.h>
  75. #if !defined(__ANDROID__)
  76. #include <sys/signal.h>
  77. #include <sys/ucontext.h>
  78. #include <sys/user.h>
  79. #include <ucontext.h>
  80. #endif
  81. #include <algorithm>
  82. #include <utility>
  83. #include <vector>
  84. #include "common/linux/linux_libc_support.h"
  85. #include "common/memory.h"
  86. #include "client/linux/log/log.h"
  87. #include "client/linux/minidump_writer/linux_dumper.h"
  88. #include "client/linux/minidump_writer/minidump_writer.h"
  89. #include "common/linux/guid_creator.h"
  90. #include "common/linux/eintr_wrapper.h"
  91. #include "third_party/lss/linux_syscall_support.h"
  92. #include "linux/sched.h"
  93. #ifndef PR_SET_PTRACER
  94. #define PR_SET_PTRACER 0x59616d61
  95. #endif
  96. // A wrapper for the tgkill syscall: send a signal to a specific thread.
  97. static int tgkill(pid_t tgid, pid_t tid, int sig) {
  98. return syscall(__NR_tgkill, tgid, tid, sig);
  99. return 0;
  100. }
  101. namespace google_breakpad {
  102. // The list of signals which we consider to be crashes. The default action for
  103. // all these signals must be Core (see man 7 signal) because we rethrow the
  104. // signal after handling it and expect that it'll be fatal.
  105. static const int kExceptionSignals[] = {
  106. SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
  107. };
  108. // We can stack multiple exception handlers. In that case, this is the global
  109. // which holds the stack.
  110. std::vector<ExceptionHandler*>* ExceptionHandler::handler_stack_ = NULL;
  111. unsigned ExceptionHandler::handler_stack_index_ = 0;
  112. pthread_mutex_t ExceptionHandler::handler_stack_mutex_ =
  113. PTHREAD_MUTEX_INITIALIZER;
  114. // Runs before crashing: normal context.
  115. ExceptionHandler::ExceptionHandler(const std::string &dump_path,
  116. FilterCallback filter,
  117. MinidumpCallback callback,
  118. void *callback_context,
  119. bool install_handler)
  120. : filter_(filter),
  121. callback_(callback),
  122. callback_context_(callback_context),
  123. handler_installed_(install_handler)
  124. {
  125. Init(dump_path, -1);
  126. }
  127. ExceptionHandler::ExceptionHandler(const std::string &dump_path,
  128. FilterCallback filter,
  129. MinidumpCallback callback,
  130. void* callback_context,
  131. bool install_handler,
  132. const int server_fd)
  133. : filter_(filter),
  134. callback_(callback),
  135. callback_context_(callback_context),
  136. handler_installed_(install_handler)
  137. {
  138. Init(dump_path, server_fd);
  139. }
  140. // Runs before crashing: normal context.
  141. ExceptionHandler::~ExceptionHandler() {
  142. UninstallHandlers();
  143. }
  144. void ExceptionHandler::Init(const std::string &dump_path,
  145. const int server_fd)
  146. {
  147. crash_handler_ = NULL;
  148. if (0 <= server_fd)
  149. crash_generation_client_
  150. .reset(CrashGenerationClient::TryCreate(server_fd));
  151. if (handler_installed_)
  152. InstallHandlers();
  153. if (!IsOutOfProcess())
  154. set_dump_path(dump_path);
  155. pthread_mutex_lock(&handler_stack_mutex_);
  156. if (handler_stack_ == NULL)
  157. handler_stack_ = new std::vector<ExceptionHandler *>;
  158. handler_stack_->push_back(this);
  159. pthread_mutex_unlock(&handler_stack_mutex_);
  160. }
  161. // Runs before crashing: normal context.
  162. bool ExceptionHandler::InstallHandlers() {
  163. // We run the signal handlers on an alternative stack because we might have
  164. // crashed because of a stack overflow.
  165. // We use this value rather than SIGSTKSZ because we would end up overrunning
  166. // such a small stack.
  167. static const unsigned kSigStackSize = 8192;
  168. stack_t stack;
  169. // Only set an alternative stack if there isn't already one, or if the current
  170. // one is too small.
  171. if (sys_sigaltstack(NULL, &stack) == -1 || !stack.ss_sp ||
  172. stack.ss_size < kSigStackSize) {
  173. memset(&stack, 0, sizeof(stack));
  174. stack.ss_sp = malloc(kSigStackSize);
  175. stack.ss_size = kSigStackSize;
  176. if (sys_sigaltstack(&stack, NULL) == -1)
  177. return false;
  178. }
  179. struct sigaction sa;
  180. memset(&sa, 0, sizeof(sa));
  181. sigemptyset(&sa.sa_mask);
  182. // mask all exception signals when we're handling one of them.
  183. for (unsigned i = 0; kExceptionSignals[i] != -1; ++i)
  184. sigaddset(&sa.sa_mask, kExceptionSignals[i]);
  185. sa.sa_sigaction = SignalHandler;
  186. sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
  187. for (unsigned i = 0; kExceptionSignals[i] != -1; ++i) {
  188. struct sigaction* old = new struct sigaction;
  189. if (sigaction(kExceptionSignals[i], &sa, old) == -1)
  190. return false;
  191. old_handlers_.push_back(std::make_pair(kExceptionSignals[i], old));
  192. }
  193. return true;
  194. }
  195. // Runs before crashing: normal context.
  196. void ExceptionHandler::UninstallHandlers() {
  197. for (unsigned i = 0; i < old_handlers_.size(); ++i) {
  198. struct sigaction *action =
  199. reinterpret_cast<struct sigaction*>(old_handlers_[i].second);
  200. sigaction(old_handlers_[i].first, action, NULL);
  201. delete action;
  202. }
  203. pthread_mutex_lock(&handler_stack_mutex_);
  204. std::vector<ExceptionHandler*>::iterator handler =
  205. std::find(handler_stack_->begin(), handler_stack_->end(), this);
  206. handler_stack_->erase(handler);
  207. pthread_mutex_unlock(&handler_stack_mutex_);
  208. old_handlers_.clear();
  209. }
  210. // Runs before crashing: normal context.
  211. void ExceptionHandler::UpdateNextID() {
  212. GUID guid;
  213. char guid_str[kGUIDStringLength + 1];
  214. if (CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str))) {
  215. next_minidump_id_ = guid_str;
  216. next_minidump_id_c_ = next_minidump_id_.c_str();
  217. char minidump_path[PATH_MAX];
  218. snprintf(minidump_path, sizeof(minidump_path), "%s/%s.dmp",
  219. dump_path_c_,
  220. guid_str);
  221. next_minidump_path_ = minidump_path;
  222. next_minidump_path_c_ = next_minidump_path_.c_str();
  223. }
  224. }
  225. // void ExceptionHandler::set_crash_handler(HandlerCallback callback) {
  226. // crash_handler_ = callback;
  227. // }
  228. // This function runs in a compromised context: see the top of the file.
  229. // Runs on the crashing thread.
  230. // static
  231. void ExceptionHandler::SignalHandler(int sig, siginfo_t* info, void* uc) {
  232. // All the exception signals are blocked at this point.
  233. pthread_mutex_lock(&handler_stack_mutex_);
  234. if (!handler_stack_->size()) {
  235. pthread_mutex_unlock(&handler_stack_mutex_);
  236. return;
  237. }
  238. for (int i = handler_stack_->size() - 1; i >= 0; --i) {
  239. if ((*handler_stack_)[i]->HandleSignal(sig, info, uc)) {
  240. // successfully handled: We are in an invalid state since an exception
  241. // signal has been delivered. We don't call the exit handlers because
  242. // they could end up corrupting on-disk state.
  243. break;
  244. }
  245. }
  246. pthread_mutex_unlock(&handler_stack_mutex_);
  247. if (info->si_pid) {
  248. // This signal was triggered by somebody sending us the signal with kill().
  249. // In order to retrigger it, we have to queue a new signal by calling
  250. // kill() ourselves.
  251. if (tgkill(getpid(), syscall(__NR_gettid), sig) < 0) {
  252. // If we failed to kill ourselves (e.g. because a sandbox disallows us
  253. // to do so), we instead resort to terminating our process. This will
  254. // result in an incorrect exit code.
  255. _exit(1);
  256. }
  257. } else {
  258. // This was a synchronous signal triggered by a hard fault (e.g. SIGSEGV).
  259. // No need to reissue the signal. It will automatically trigger again,
  260. // when we return from the signal handler.
  261. }
  262. // As soon as we return from the signal handler, our signal will become
  263. // unmasked. At that time, we will get terminated with the same signal that
  264. // was triggered originally. This allows our parent to know that we crashed.
  265. // The default action for all the signals which we catch is Core, so
  266. // this is the end of us.
  267. signal(sig, SIG_DFL);
  268. }
  269. struct ThreadArgument {
  270. pid_t pid; // the crashing process
  271. ExceptionHandler* handler;
  272. const void* context; // a CrashContext structure
  273. size_t context_size;
  274. };
  275. // This is the entry function for the cloned process. We are in a compromised
  276. // context here: see the top of the file.
  277. // static
  278. int ExceptionHandler::ThreadEntry(void *arg) {
  279. const ThreadArgument *thread_arg = reinterpret_cast<ThreadArgument*>(arg);
  280. // Block here until the crashing process unblocks us when
  281. // we're allowed to use ptrace
  282. thread_arg->handler->WaitForContinueSignal();
  283. return thread_arg->handler->DoDump(thread_arg->pid, thread_arg->context,
  284. thread_arg->context_size) == false;
  285. }
  286. // This function runs in a compromised context: see the top of the file.
  287. // Runs on the crashing thread.
  288. bool ExceptionHandler::HandleSignal(int sig, siginfo_t* info, void* uc) {
  289. if (filter_ && !filter_(callback_context_))
  290. return false;
  291. // Allow ourselves to be dumped if the signal is trusted.
  292. bool signal_trusted = info->si_code > 0;
  293. bool signal_pid_trusted = info->si_code == SI_USER ||
  294. info->si_code == SI_TKILL;
  295. if (signal_trusted || (signal_pid_trusted && info->si_pid == getpid())) {
  296. sys_prctl(PR_SET_DUMPABLE, 1);
  297. }
  298. CrashContext context;
  299. memcpy(&context.siginfo, info, sizeof(siginfo_t));
  300. memcpy(&context.context, uc, sizeof(struct ucontext));
  301. #if !defined(__ARM_EABI__)
  302. // FP state is not part of user ABI on ARM Linux.
  303. struct ucontext *uc_ptr = (struct ucontext*)uc;
  304. if (uc_ptr->uc_mcontext.fpregs) {
  305. memcpy(&context.float_state,
  306. uc_ptr->uc_mcontext.fpregs,
  307. sizeof(context.float_state));
  308. }
  309. #endif
  310. context.tid = syscall(__NR_gettid);
  311. if (crash_handler_ != NULL) {
  312. if (crash_handler_(&context, sizeof(context),
  313. callback_context_)) {
  314. return true;
  315. }
  316. }
  317. return GenerateDump(&context);
  318. }
  319. // This function may run in a compromised context: see the top of the file.
  320. bool ExceptionHandler::GenerateDump(CrashContext *context) {
  321. if (IsOutOfProcess())
  322. return crash_generation_client_->RequestDump(context, sizeof(*context));
  323. static const unsigned kChildStackSize = 8000;
  324. PageAllocator allocator;
  325. uint8_t* stack = (uint8_t*) allocator.Alloc(kChildStackSize);
  326. if (!stack)
  327. return false;
  328. // clone() needs the top-most address. (scrub just to be safe)
  329. stack += kChildStackSize;
  330. my_memset(stack - 16, 0, 16);
  331. ThreadArgument thread_arg;
  332. thread_arg.handler = this;
  333. thread_arg.pid = getpid();
  334. thread_arg.context = context;
  335. thread_arg.context_size = sizeof(*context);
  336. // We need to explicitly enable ptrace of parent processes on some
  337. // kernels, but we need to know the PID of the cloned process before we
  338. // can do this. Create a pipe here which we can use to block the
  339. // cloned process after creating it, until we have explicitly enabled ptrace
  340. if(sys_pipe(fdes) == -1) {
  341. // Creating the pipe failed. We'll log an error but carry on anyway,
  342. // as we'll probably still get a useful crash report. All that will happen
  343. // is the write() and read() calls will fail with EBADF
  344. static const char no_pipe_msg[] = "ExceptionHandler::GenerateDump \
  345. sys_pipe failed:";
  346. logger::write(no_pipe_msg, sizeof(no_pipe_msg) - 1);
  347. logger::write(strerror(errno), strlen(strerror(errno)));
  348. logger::write("\n", 1);
  349. }
  350. #if defined(__ANDROID__)
  351. const pid_t child = clone(
  352. ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
  353. &thread_arg);
  354. #else
  355. const pid_t child = sys_clone(
  356. ThreadEntry, stack, CLONE_FILES | CLONE_FS | CLONE_UNTRACED,
  357. &thread_arg, NULL, NULL, NULL);
  358. #endif
  359. int r, status;
  360. // Allow the child to ptrace us
  361. sys_prctl(PR_SET_PTRACER, child);
  362. SendContinueSignalToChild();
  363. do {
  364. r = sys_waitpid(child, &status, __WALL);
  365. } while (r == -1 && errno == EINTR);
  366. sys_close(fdes[0]);
  367. sys_close(fdes[1]);
  368. if (r == -1) {
  369. static const char msg[] = "ExceptionHandler::GenerateDump waitpid failed:";
  370. logger::write(msg, sizeof(msg) - 1);
  371. logger::write(strerror(errno), strlen(strerror(errno)));
  372. logger::write("\n", 1);
  373. }
  374. bool success = r != -1 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
  375. if (callback_)
  376. success = callback_(dump_path_c_, next_minidump_id_c_,
  377. callback_context_, success);
  378. return success;
  379. }
  380. // This function runs in a compromised context: see the top of the file.
  381. void ExceptionHandler::SendContinueSignalToChild() {
  382. static const char okToContinueMessage = 'a';
  383. int r;
  384. r = HANDLE_EINTR(sys_write(fdes[1], &okToContinueMessage, sizeof(char)));
  385. if(r == -1) {
  386. static const char msg[] = "ExceptionHandler::SendContinueSignalToChild \
  387. sys_write failed:";
  388. logger::write(msg, sizeof(msg) - 1);
  389. logger::write(strerror(errno), strlen(strerror(errno)));
  390. logger::write("\n", 1);
  391. }
  392. }
  393. // This function runs in a compromised context: see the top of the file.
  394. // Runs on the cloned process.
  395. void ExceptionHandler::WaitForContinueSignal() {
  396. int r;
  397. char receivedMessage;
  398. r = HANDLE_EINTR(sys_read(fdes[0], &receivedMessage, sizeof(char)));
  399. if(r == -1) {
  400. static const char msg[] = "ExceptionHandler::WaitForContinueSignal \
  401. sys_read failed:";
  402. logger::write(msg, sizeof(msg) - 1);
  403. logger::write(strerror(errno), strlen(strerror(errno)));
  404. logger::write("\n", 1);
  405. }
  406. }
  407. // This function runs in a compromised context: see the top of the file.
  408. // Runs on the cloned process.
  409. bool ExceptionHandler::DoDump(pid_t crashing_process, const void* context,
  410. size_t context_size) {
  411. return google_breakpad::WriteMinidump(next_minidump_path_c_,
  412. crashing_process,
  413. context,
  414. context_size,
  415. mapping_list_);
  416. }
  417. // static
  418. bool ExceptionHandler::WriteMinidump(const std::string &dump_path,
  419. MinidumpCallback callback,
  420. void* callback_context) {
  421. ExceptionHandler eh(dump_path, NULL, callback, callback_context, false);
  422. return eh.WriteMinidump();
  423. }
  424. bool ExceptionHandler::WriteMinidump() {
  425. #if !defined(__ARM_EABI__)
  426. // Allow ourselves to be dumped.
  427. sys_prctl(PR_SET_DUMPABLE, 1);
  428. CrashContext context;
  429. int getcontext_result = getcontext(&context.context);
  430. if (getcontext_result)
  431. return false;
  432. memcpy(&context.float_state, context.context.uc_mcontext.fpregs,
  433. sizeof(context.float_state));
  434. context.tid = sys_gettid();
  435. bool success = GenerateDump(&context);
  436. UpdateNextID();
  437. return success;
  438. #else
  439. return false;
  440. #endif // !defined(__ARM_EABI__)
  441. }
  442. void ExceptionHandler::AddMappingInfo(const std::string& name,
  443. const u_int8_t identifier[sizeof(MDGUID)],
  444. uintptr_t start_address,
  445. size_t mapping_size,
  446. size_t file_offset) {
  447. MappingInfo info;
  448. info.start_addr = start_address;
  449. info.size = mapping_size;
  450. info.offset = file_offset;
  451. strncpy(info.name, name.c_str(), sizeof(info.name) - 1);
  452. info.name[sizeof(info.name) - 1] = '\0';
  453. MappingEntry mapping;
  454. mapping.first = info;
  455. memcpy(mapping.second, identifier, sizeof(MDGUID));
  456. mapping_list_.push_back(mapping);
  457. }
  458. } // namespace google_breakpad