pthread_cancel.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "pthread_impl.h"
  2. #include "syscall.h"
  3. #include "libc.h"
  4. void __cancel()
  5. {
  6. pthread_exit(PTHREAD_CANCELED);
  7. }
  8. /* If __syscall_cp_asm has adjusted the stack pointer, it must provide a
  9. * definition of __cp_cancel to undo those adjustments and call __cancel.
  10. * Otherwise, __cancel provides a definition for __cp_cancel. */
  11. weak_alias(__cancel, __cp_cancel);
  12. long __syscall_cp_asm(volatile void *, syscall_arg_t,
  13. syscall_arg_t, syscall_arg_t, syscall_arg_t,
  14. syscall_arg_t, syscall_arg_t, syscall_arg_t);
  15. long __syscall_cp_c(syscall_arg_t nr,
  16. syscall_arg_t u, syscall_arg_t v, syscall_arg_t w,
  17. syscall_arg_t x, syscall_arg_t y, syscall_arg_t z)
  18. {
  19. pthread_t self;
  20. long r;
  21. if (!libc.has_thread_pointer || (self = __pthread_self())->canceldisable)
  22. return __syscall(nr, u, v, w, x, y, z);
  23. r = __syscall_cp_asm(&self->cancel, nr, u, v, w, x, y, z);
  24. if (r==-EINTR && nr!=SYS_close && self->cancel && !self->canceldisable)
  25. __cancel();
  26. return r;
  27. }
  28. static void _sigaddset(sigset_t *set, int sig)
  29. {
  30. unsigned s = sig-1;
  31. set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
  32. }
  33. static void cancel_handler(int sig, siginfo_t *si, void *ctx)
  34. {
  35. pthread_t self = __pthread_self();
  36. ucontext_t *uc = ctx;
  37. const char *ip = ((char **)&uc->uc_mcontext)[CANCEL_REG_IP];
  38. extern const char __cp_begin[1], __cp_end[1];
  39. a_barrier();
  40. if (!self->cancel || self->canceldisable) return;
  41. _sigaddset(&uc->uc_sigmask, SIGCANCEL);
  42. if (self->cancelasync || ip >= __cp_begin && ip < __cp_end) {
  43. self->canceldisable = 1;
  44. pthread_sigmask(SIG_SETMASK, &uc->uc_sigmask, 0);
  45. __cancel();
  46. }
  47. __syscall(SYS_tkill, self->tid, SIGCANCEL);
  48. }
  49. void __testcancel()
  50. {
  51. if (!libc.has_thread_pointer) return;
  52. pthread_t self = __pthread_self();
  53. if (self->cancel && !self->canceldisable)
  54. __cancel();
  55. }
  56. static void init_cancellation()
  57. {
  58. struct sigaction sa = {
  59. .sa_flags = SA_SIGINFO | SA_RESTART,
  60. .sa_sigaction = cancel_handler
  61. };
  62. sigfillset(&sa.sa_mask);
  63. __libc_sigaction(SIGCANCEL, &sa, 0);
  64. }
  65. int pthread_cancel(pthread_t t)
  66. {
  67. static int init;
  68. if (!init) {
  69. init_cancellation();
  70. init = 1;
  71. }
  72. a_store(&t->cancel, 1);
  73. return pthread_kill(t, SIGCANCEL);
  74. }