cancel_impl.c 1.8 KB

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