cancel_impl.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "pthread_impl.h"
  2. void __cancel()
  3. {
  4. pthread_t self = __pthread_self();
  5. self->canceldisable = 1;
  6. self->cancelasync = 0;
  7. pthread_exit(PTHREAD_CANCELED);
  8. }
  9. long __syscall_cp_asm(volatile void *, long, long, long, long, long, long, long);
  10. long (__syscall_cp)(long nr, long u, long v, long w, long x, long y, long z)
  11. {
  12. pthread_t self;
  13. long r;
  14. if (!libc.main_thread || (self = __pthread_self())->canceldisable)
  15. return __syscall(nr, u, v, w, x, y, z);
  16. r = __syscall_cp_asm(&self->cancel, nr, u, v, w, x, y, z);
  17. if (r==-EINTR && nr!=SYS_close && self->cancel && !self->canceldisable)
  18. __cancel();
  19. return r;
  20. }
  21. static void _sigaddset(sigset_t *set, int sig)
  22. {
  23. unsigned s = sig-1;
  24. set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
  25. }
  26. static void cancel_handler(int sig, siginfo_t *si, void *ctx)
  27. {
  28. pthread_t self = __pthread_self();
  29. ucontext_t *uc = ctx;
  30. const char *ip = ((char **)&uc->uc_mcontext)[CANCEL_REG_IP];
  31. extern const char __cp_begin[1], __cp_end[1];
  32. if (!self->cancel || self->canceldisable) return;
  33. _sigaddset(&uc->uc_sigmask, SIGCANCEL);
  34. if (self->cancelasync || ip >= __cp_begin && ip < __cp_end) {
  35. self->canceldisable = 1;
  36. pthread_sigmask(SIG_SETMASK, &uc->uc_sigmask, 0);
  37. __cancel();
  38. }
  39. __syscall(SYS_tgkill, self->pid, self->tid, SIGCANCEL);
  40. }
  41. void __testcancel()
  42. {
  43. pthread_t self = pthread_self();
  44. if (self->cancel && !self->canceldisable)
  45. __cancel();
  46. }
  47. static void init_cancellation()
  48. {
  49. struct sigaction sa = {
  50. .sa_flags = SA_SIGINFO | SA_RESTART,
  51. .sa_sigaction = cancel_handler
  52. };
  53. sigfillset(&sa.sa_mask);
  54. __libc_sigaction(SIGCANCEL, &sa, 0);
  55. }
  56. int pthread_cancel(pthread_t t)
  57. {
  58. static int init;
  59. if (!init) {
  60. init_cancellation();
  61. init = 1;
  62. }
  63. a_store(&t->cancel, 1);
  64. return pthread_kill(t, SIGCANCEL);
  65. }